There are occasions where you need to wait for a particular condition to apply before being able to perform related processing but where there is no event triggered when the condition applies. The only way we can tell when the condition is met in this case is to test for it at intervals.

The following poll function (which appears on various sites) does this while providing for several options. The poll function takes three mandatory and two optional parameters to provide maximum polling flexibility.

The three mandatory parameters are all functions. The first of these returns the condition you are testing for - that way the code can test if the condition is met by calling that first function. The second parameter identifies the function that is to be called when the condition is met. So this function contains what we would have called from an event listener had an appropriate event been available to listen for. The third parameter is the function that will get called if the condition is not met within a reasonable time. This error function will be passed an error object identifying the error should it be called.

The fourth parameter - the first optional one - specifies the amount of time in milliseconds that the polling is allowed to continue for. If the condition is not met within this amount of time (or 2 seconds if the parameter is omitted) then polling for the condition will cease and the error function in the third parameter will be called.

The fifth parameter identifies how frequently the condition should be tested for (which will be 1/10th second if the parameter is omitted).

When the poll function is called it will first calculate the maximum time it should run to and set the interval for polling. It then calls a named IIFE to do the rest of the processing. This function expression first tests if the condition is met and if so it runs the callback function in the second parameter. If the condition is not met but the maximum time is not yet reached then setTimeout is used to recursively execute the function again after the specified interval. If the maximum tine has expired then the error processing is called.

function poll(fn, callback, errback, timeout, interval) {
    var endTime = Number(new Date()) + (timeout || 2000);
    interval = interval || 100;
    (function p() {
            if(fn()) {
            else if (Number(new Date()) < endTime) {
                setTimeout(p, interval);
            else {
                errback(new Error('timed out for ' + fn + ': ' + arguments));


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow