很多时候需要在一定时间后多次执行一个函数。例如,您可能希望在给定时间后刷新屏幕。Prototype 提供了一种简单的机制来使用PeriodicalExecuter对象来实现它。
PeriodicalExecuter提供的优势在于它可以保护您免受回调函数的多次并行执行。
创建一个 PeriodicalExecuter
构造函数有两个参数:
- 回调函数。
- 执行之间的间隔(以秒为单位)。
一旦启动,PeriodicalExecuter 将无限期触发,直到页面卸载或使用stop()方法停止执行程序。
例子
以下是每 5 秒后弹出一个对话框的示例,直到您按“取消”按钮停止它。
HTML
x
22
22
1
<html>
2
<head>
3
<title>Prototype examples</title>
4
<script type = "text/javascript" src = "https://cdn.bootcdn.net/ajax/libs/prototype/1.7.3/prototype.min.js"></script>
5
6
<script>
7
function startExec() {
8
new PeriodicalExecuter(function(pe) {
9
if (!confirm('Want me to annoy you again later?'))
10
pe.stop();
11
}, 5);
12
}
13
</script>
14
</head>
15
16
<body>
17
<p>Click start button to start periodic executer:</p>
18
<br />
19
<br />
20
<input type = "button" value = "start" onclick = "startExec();"/>
21
</body>
22
</html>
阅读剩余 31%
作者:terry,如若转载,请注明出处:https://www.web176.com/prototype/8216.html