[javascript] How to pause javascript code execution for 2 seconds

I want to stop execution for 2 seconds. So is this, but now follows a code block:

<html>
   <head>
      <title> HW 10.12 </title>
      <script type="text/javascript">
         for (var i = 1; i <= 5; i++) {
             document.write(i);
             sleep(2); //for the first time loop is excute and sleep for 2 seconds        
         };
      </script>
   </head>
   <body></body>
</html>

For the first time loop is excute and sleep for 2 seconds. I want to stop execution for two seconds?

This question is related to javascript

The answer is


Javascript is single-threaded, so by nature there should not be a sleep function because sleeping will block the thread. setTimeout is a way to get around this by posting an event to the queue to be executed later without blocking the thread. But if you want a true sleep function, you can write something like this:

function sleep(miliseconds) {
   var currentTime = new Date().getTime();

   while (currentTime + miliseconds >= new Date().getTime()) {
   }
}

Note: The above code is NOT recommended.


This Link might be helpful for you.

Every time I've wanted a sleep in the middle of my function, I refactored to use a setTimeout().


There's no way to stop execution of your code as you would do with a procedural language. You can instead make use of setTimeout and some trickery to get a parametrized timeout:

for (var i = 1; i <= 5; i++) {
    var tick = function(i) {
        return function() {
            console.log(i);
        }
    };
    setTimeout(tick(i), 500 * i);
}

Demo here: http://jsfiddle.net/hW7Ch/


There's no (safe) way to pause execution. You can, however, do something like this using setTimeout:

function writeNext(i)
{
    document.write(i);

    if(i == 5)
        return;

    setTimeout(function()
    {
        writeNext(i + 1);

    }, 2000);
}

writeNext(1);

You can use setTimeout to do this

function myFunction() {
    // your code to run after the timeout
}

// stop for sometime if needed
setTimeout(myFunction, 5000);