28 April, 2009

window.waitUntil

2009/08/23 Update:
This is only really useful if you need to do asynchronous calls 11 or more times. If you only need to make a few calls, it would be better to just use the (function () {}()); construct.

Here is a new function I have recently created:

"use strict";
var waitUntil = function anon(func, ms) {
    ms = ms || 100;
    if (func() !== true) {
        return setTimeout(function () {
            anon(func, ms);
        }, ms);
    }
};

I don't know about you, but in my code I have to frequently test a condition... but do so asynchronously. You can do this with setTimeout, but it requires a lot of syntax and work to get it right. The above function attempts to ease this a little.

You call it like so:

waitUntil(function () {
    if (test === 5) {
        alert("Done!");
        return true;
    }
});
This is the same as if I had done:
(function anon() {
    if (test === 5) {
        alert("Done");
    } else {
        setTimeout(anon, 100);
    }
}());

Not a huge difference, but still useful when you need to perform such checks on a regular basis. waitUntil accepts two arguments:

  1. This should be a function. waitUntil will continue executing this function until it returns true, which tells waitUntil to stop.
  2. This should be a number. This is how often waitUntil will run the function, in milliseconds. The default is 100.

In addition, waitUntil returns a setTimeout, so you can use clearTimeout to halt the check at any time:

var timer = waitUntil(function () {
    if (test === 5) {
        alert("Done!");
        return true;
    }
}, 300);
clearTimeout(timer);

[LINK] The unit tests.

No comments:

Post a Comment