PeriodicalExecuter Atom feed

This is a simple facility for periodical execution of a function. This essentially encapsulates the native clearInterval/setInterval mechanism found in native Window objects.

The only notable advantage provided by PeriodicalExecuter is that it shields you against multiple parallel executions of the callback function, should it take longer than the given interval to execute (it maintains an internal “running” flag, which is shielded against exceptions in the callback function). 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.

Of course, one might very well argue that using an actual object, not needing to maintain a global interval handle, etc. constitute notable advantages as well.

Creating a PeriodicalExecuter

The constructor takes two arguments: the callback function, and the interval (in seconds) between executions. Once launched, a PeriodicalExecuter triggers indefinitely, until the page unloads (which browsers usually take as an opportunity to clear all intervals and timers) or the executer is manually stopped.


// Campfire style :-)
new PeriodicalExecuter(pollChatRoom, 3);

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...

Methods

stop

stop()

Stops the periodical executer (there will be no further triggers).