Prototype - 定期执行

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

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

创建 PeriodicalExecuter

构造函数采用两个参数 −

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

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

示例

以下示例将每 5 秒弹出一个对话框,直到您按"取消"按钮将其停止。

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.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>

输出