当前位置: 首页 > 图文教程 > 网络编程 > Javascript > Prototype PeriodicalExecuter对象 学习

Javascript
javascript IFrame 强制刷新代码
JQuery 学习笔记 选择器之一
JQuery 学习笔记 选择器之二
JQuery 学习笔记 选择器之三
JQuery 学习笔记 element属性控制
Prototype 工具函数 学习
Prototype Selector对象学习
用JQuery 实现AJAX加载XML并解析的脚本
jquery 表单下所有元素的隐藏
javascript 动态table添加colspan\rowspan 参数的方法
利用javascript/jquery对上传文件格式过滤的方法
javaScript 判断字符串是否为数字的简单方法
jquery 将disabled的元素置为enabled的三种方法
javascript 解析后的xml对象的读取方法细解
IE中radio 或checkbox的checked属性初始状态下不能选中显示问题
javascript 一个函数对同一元素的多个事件响应
对象特征检测法判断浏览器对javascript对象的支持
javaScript Array(数组)相关方法简述
js 字符串操作函数
JavaScript中null与undefined分析

Javascript 中的 Prototype PeriodicalExecuter对象 学习


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 163 ::
收藏到网摘: n/a

这个对象就是可以周期性的执行某个方法,但是在它内部维持了一个状态,可以防止由于某些原因一次调用没执行,然后下一次调用又来了,这样会造成连续执行两次方法。上面的第二断英文就是这个意思。 This is a simple facility for periodical execution of a function. This essentially encapsulates the native clearInterval/setInterval mechanism found in native Window objects.
This is especially useful if you use one to interact with the user at given intervals (e.g. use a prompt or confirm call): this will avoid multiple message boxes all waiting to be actioned.

这个对象就是可以周期性的执行某个方法,但是在它内部维持了一个状态,可以防止由于某些原因一次调用没执行,然后下一次调用又来了,这样会造成连续执行两次方法。上面的第二断英文就是这个意思。
帮助文档上说这个对象只提供了一个方法stop,但是在我看的源码里还提供了一个事件onTimerEvent,应该可以在某个时候触发这个事件。但帮助文档上没有给出示例。
这个对象源码比较简单,这里直接贴出来了,就不再注释了:
复制代码 代码如下:

var PeriodicalExecuter = Class.create({
initialize: function(callback, frequency) {
this.callback = callback;
this.frequency = frequency;
this.currentlyExecuting = false;
this.registerCallback();
},
registerCallback: function() {
this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
},
execute: function() {
this.callback(this);
},
stop: function() {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = null;
},
onTimerEvent: function() {
if (!this.currentlyExecuting) {
try {
this.currentlyExecuting = true;
this.execute();
} catch(e) {
/* empty catch for clients that don't support try/finally */
}
finally {
this.currentlyExecuting = false;
}
}
}
});

看一下示例:
复制代码 代码如下:

new PeriodicalExecuter(function(pe) {
if (!confirm('Want me to annoy you again later?'))
pe.stop(); },
5);
// Note that there won't be a stack of such messages if the user takes too long
// answering to the question...