sleep() in Javascript

nomind picture nomind · Jun 29, 2010 · Viewed 36.2k times · Source

Suppose I want to block Javascript execution for certain time for some weird reason, how can I do that. There is no sleep() in JS. Pls don't say do a while() loop because that's bad. I can do a window.showModalDialog and put a window.close in the modal dialog with setTimeout of very small time so that the user doesn't notice the dialog. This will be like sleep for small time period and I can call this multiple time if needed. Is there some other way?

To elaborate, my use case is that HTML5 SQL Database has given async api's but I want to use it for a samll webapp for which the store will never be big. So there is no need of an async api because the queries on the small store will run on the client side. So I want to write an ORM with sync api so that developers can use it more easily. To bridge this async to sync api, I need something like sleep.

Answer

Russ Cam picture Russ Cam · Jun 29, 2010

window.setTimeout or window.setInterval are pretty much your only friends.

An example of how to use setTimeout to recursively call a function that sets another timeout is as follows

function go() {
    if (go.count < 4) {
        // logs 1, 2, 3 to firebug console at 1 second intervals
        console.log(go.count++);
        window.setTimeout(go, 1000);
    }
}
go.count = 1;

go();

You may choose to capture the timeoutID to use with window.clearTimeout if you need to clear the timeout prior to it finishing.

Note that neither window.setTimeout nor window.setInterval block execution of other script - I don't believe that this is possible with JavaScript in it's current guise. There are ways that could be coded to mimic UI blocking, such as using showModalDialog or having some global blocking boolean which are about as near as you can get I'm afraid.