Prototype – 定期执行

很多时候需要在一定时间后多次执行一个函数。例如,您可能希望在给定时间后刷新屏幕。Prototype 提供了一种简单的机制来使用PeriodicalExecuter对象来实现它。

PeriodicalExecuter提供的优势在于它可以保护您免受回调函数的多次并行执行。

创建一个 PeriodicalExecuter

构造函数有两个参数:

  • 回调函数。
  • 执行之间的间隔(以秒为单位)。

一旦启动,PeriodicalExecuter 将无限期触发,直到页面卸载或使用stop()方法停止执行程序。

例子

以下是每 5 秒后弹出一个对话框的示例,直到您按“取消”按钮停止它。

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "https://cdn.bootcdn.net/ajax/libs/prototype/1.7.3/prototype.min.js"></script>
      
      <script>
         function startExec() {
            new PeriodicalExecuter(function(pe) {
               if (!confirm('Want me to annoy you again later?'))
               pe.stop();
            }, 5);
         }
      </script>
   </head>

   <body>
      <p>Click start button to start periodic executer:</p>
      <br />
      <br />
      <input type = "button" value = "start" onclick = "startExec();"/>
   </body>
</html>

作者:terry,如若转载,请注明出处:https://www.web176.com/prototype/8216.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2023年1月16日 上午10:08
下一篇 2023年1月17日 下午5:46

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注