116

I want to stop execution for 2 seconds.

<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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
abdullah sheikh
  • 1,279
  • 2
  • 8
  • 3
  • for (var i = 1; i <=5; i++) { document.write(i); sleep(4); } – abdullah sheikh May 18 '13 at 11:41
  • Why do you want to pause execution for two, or any number of, seconds? – David Thomas May 18 '13 at 11:43
  • 1
    You can edit your question to fix the source code. – knuton May 18 '13 at 11:43
  • http://stackoverflow.com/questions/1183872/put-a-delay-in-javascript?answertab=oldest#tab-top – Ketan Modi May 18 '13 at 11:52
  • The big mix up here is that you used the term "stop" when you really wanted to use "sleep" - that's why this is a duplicate question. For those who really want a stop, your best bet is a stepper that runs over and over until the delay is reached. I'd post the code but this answer is closed. – Jacksonkr Sep 27 '18 at 23:43

5 Answers5

146

Before using this code, please read all comments.

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.

MeSo2
  • 450
  • 1
  • 7
  • 18
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • 36
    **DONT LIKE THAT!!!** That causes WHOLE TAB freeze (also other tabs affected too) during that time , because `while` command is being executed unlimited times by CPU, causing to freeze. See practical example - https://jsfiddle.net/mn6yagqx/ (test yourself) – T.Todua Dec 20 '17 at 17:45
  • 38
    @T.Todua: That's why the post did not recommend it. This is just a workaround in case people want to do it anyway – Khanh TO Dec 23 '17 at 02:36
  • 3
    I wonder how many people have used this block of code already without looking at the comment of @T.Todua – Khan Shahrukh Jul 19 '18 at 12:57
  • 9
    This was useful to simulate a very busy Web Worker, so I could confirm how messages get queued and processed when the worker is busy. – whitehat101 Oct 07 '18 at 22:01
  • 2
    Still useful to introduce a temporary delay for debugging mocha tests, for example. – demisx Mar 03 '19 at 17:36
  • Should write a comment above the code block not to use this piece of code – Guillaume A. Jul 30 '19 at 08:03
70

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);
James M
  • 18,506
  • 3
  • 48
  • 56
  • This will not pause execution but delay `writeNext` function output. If there are lines of code after `writeNext(1);` they will be executed right away. – user487772 Aug 08 '21 at 18:40
51

You can use setTimeout to do this

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

// stop for sometime if needed
setTimeout(myFunction, 2000);
Serge Stroobandt
  • 28,495
  • 9
  • 107
  • 102
Sachin
  • 40,216
  • 7
  • 90
  • 102
6

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().

Community
  • 1
  • 1
Saman Gholami
  • 3,416
  • 7
  • 30
  • 71
4

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/

sixFingers
  • 1,285
  • 8
  • 13