Home  >  Article  >  Web Front-end  >  Prototype PeriodicalExecuter object learning_prototype

Prototype PeriodicalExecuter object learning_prototype

WBOY
WBOYOriginal
2016-05-16 18:49:471004browse

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.


This object can execute a method periodically, but maintains a state inside it , can prevent one call from being executed due to some reasons, and then the next call comes again, which will cause the method to be executed twice in a row. The second sentence above in English means this.

The help document says that this object only provides one method stop, but the source code I looked at also provides an event onTimerEvent, which should be triggered at some point. But there are no examples given in the help documentation.

The source code of this object is relatively simple. It is posted directly here without any comments:

Copy code The code is as follows:

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;
}
}
}
});

Look at the example:
Copy the code The code is as follows:

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...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn