notoriousb1t

Short lived timer JavaScript function

Here is some code I wrote for an answer on /r/javascript on reddit. It periodically checks for some condition for a maximum amount of time. It should be handy if you couldn't otherwise specify a callback when an asynchronous task is launched.

Here is the code:

    function timer(options) {
        var interval = options.interval || 250;
        var remaining = options.timeout || 5000;
        var until = options.until || function () { };
        var done = options.done || function () { };
        var scheduledTask;
        scheduledTask = setInterval(function(){
                remaining -= interval;
                var finishTask = until(remaining);
                if (finishTask !== undefined) {
                    window.clearInterval(scheduledTask);
                    done(finishTask);
                }
                if (remaining < 1){
                   window.clearInterval(scheduledTask);
                   done('timed out');
                }
        }, interval);
    }

How do I use it?

    timer({
        interval: 250,
        timeout: 4000,
        until: function(remaining) {
            console.log('do something')
            if (remaining < 2000) {
                // return anything when you want to stop execution
                return 'done';
            }
        },
        done: function(message) {
            console.log(message);
        }
    })

Click here to see it in action

What's actually happening?

  • timer expects to get an interval,  a (maximum) timeout, an until function to call each time the interval is hit, and a done function when either the timeout happens, or any value other than undefined is returned from until
  • timer sets defaults for whatever properties were not specified
  • timer then uses the setInterval function in JavaScript to perform steps each time the interval ticks
  • Each tick..
    • reduces the remaining time by the interval
    • captures a value from until
    • checks if until returned a value other than undefined.  If something was returned it call done and passes whatever value was returned checks if there is any remaining time.  If there isn't, It calls done and passes 'time out'
    • If done is called, timer calls clearTimeout to stop setInterval