原型 - 週期執行



很多時候,需要在特定時間段後多次執行一個函式。例如,您可能想要在指定時間後重新整理螢幕。原型提供了一個使用 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>

輸出

廣告
© . All rights reserved.