很多时候需要在一定时间后多次执行一个函数。例如,您可能希望在给定时间后刷新屏幕。Prototype 提供了一种简单的机制来使用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>