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.
Sleep() With the help of Sleep() we can make a function to pause execution for a fixed amount of time. In programming languages such as C and Php we would call sleep(sec). Java has thread.
To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.
Many programming languages have a sleep function that will delay a program's execution for a given number of seconds. However, this functionality is absent from JavaScript due to its asynchronous nature.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With