This is a simple facility for periodical execution of a function. This essentially encapsulates the native clearInterval/setInterval mechanic 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 periodically execute a method, but it maintains a state inside it, which can prevent one call from being executed for some reason, and then the next call comes again, this will cause two consecutive methods to be executed. This is the second break in English.
The help document says that this object only provides a method to stop, but in the source code I see, it also provides an event onTimerEvent, which should be able to trigger this event at some time. However, no examples are provided in the help document.
The source code of this object is relatively simple. If it is directly posted here, it will not be commented out:
Copy codeThe 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.exe cute ();
} Catch (e ){
/* Empty catch for clients that don't support try/finally */
}
Finally {
This. currentlyExecuting = false;
}
}
}
});
Take a look at the example:
Copy codeThe 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...