How To Sleep With Javascript

If you’re a .NET developer you are probably familiar with the Thread.Sleep() method, which allows you to pause further execution of your code until a defined period of time has passed.
Unfortunately there is no direct equivalent for sleep with javascript, but there are several alternatives to get similar results, but they will probably require you to modify your code slightly to take advantage of it.
setTimeout() is the most common solution.
It allows you to execute some code after a set time.

The format is as follows:

 setTimeout(function(){ 
     //Do stuff after the set wait time 
 },timeInMillisecondsToWait)

Once problem with this approach is that the javascript simply won’t pause execution until after the wait time, it will just carry on processing everything else and whenever the timeout you’ve set has elapsed it will execute the code within the setTimeout function.
For Example:

        function test2() {

            alert("1");

            setTimeout(function () {
                alert("2");
            }, 10000);
           
            alert("3");
        }

alert(“1”) will execute, skip over alert(“2”), execute alert 3, then wait 10 seconds (From the point that setTimeout was hit) then finally execute alert(“2”).
This is probably not what you would have wanted.
In order to make sure that your code executes in the correct order, you’ll need to add the rest of your code within the body of the setTimeout method, which as you can imagine, could get messy if you have code which relies on additional delays.

        function test3() {
            alert("1");

            setTimeout(function () {
                alert("2");
                alert("3");
            }, 10000);         
        }

Your best bet is to encapsulate your code into functions where appropriate, making it look a bit cleaner without sacrificing functionality.

If you enjoyed this article, please consider giving it a +1

Tags: javascript, sleep, delay, wait

Published: 7/6/2014 1:18:01 PM
By: Stephen Warren