8

Is there a simple way to pause the script in Javascript? I'm looking for the javascript equivalent of time.sleep(1) in Python. I do NOT want setTimeout(continueExecution, 10), or anything with getTime. Can this be done?

EDIT: It wasn't quite as easy, but I think I can get it done with setTimeout

tkbx
  • 15,602
  • 32
  • 87
  • 122
  • 3
    The programming model in JavaScript in general is non-blocking, so you wont have any blocking call like a `sleep()` function. – Sirko Mar 16 '12 at 14:09
  • 1
    No --- See also [this maybe duplicate thread](http://stackoverflow.com/questions/1277070/is-there-an-equivalent-javascript-or-jquery-sleep-function) – Neysor Mar 16 '12 at 14:09
  • Why don't you want to use `setTimeout`? – gen_Eric Mar 16 '12 at 14:10
  • 4
    Just out of curiosity - what are your reasons for wanting a sleep method? Chances are if you want a sleep method there's a less hacky way to accomplish it. :] (not that there is a sleep method) – Snuffleupagus Mar 16 '12 at 14:13
  • Check out this thread: http://stackoverflow.com/questions/5832276/why-there-is-no-sleep-functionality-in-javascript-when-there-is-settimeout-and-s – Josh Siok Mar 16 '12 at 14:13
  • I'm sure you can improve on this question's title. – Lightness Races in Orbit Mar 16 '12 at 14:24

8 Answers8

19

JavaScript is usually ran in a single thread using an event-loop. This is why you can't do any "Thread.sleep". If you could it would freeze everything else for that duration and believe me you don't want to do that. This is why almost everything in JavaScript runs using non-blocking IO and that's why the only way you can do delay execution is by using setTimeout or setInterval.

HoLyVieR
  • 10,985
  • 5
  • 42
  • 67
9

without setTimeout, you could always loop until you reach a desired date time:

Disclaimers: This is untested. Since javascript is single-threaded, this WILL freeze your entire browser while looping. See other questions for more information on this topic.

var delay = 5; // 5 second delay
var now = new Date();
var desiredTime = new Date().setSeconds(now.getSeconds() + delay);

while (now < desiredTime) {
    now = new Date(); // update the current time
}

// continue execution
Community
  • 1
  • 1
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • I was just writing something similar. – geekchic Mar 16 '12 at 14:15
  • It clearly is untested, because this would just freeze your browser for that duration if you would attempt to do that. Also the OP has explicitly said that he doesn't want any "getTime" like method. – HoLyVieR Mar 16 '12 at 14:19
  • 4
    @HoLyVieR the OP stated he wanted to "pause the script" - if you pause javascript, you're blocking the browser. period. – jbabey Mar 16 '12 at 14:20
  • @HoLyVieR: The OP may have said he doesn't want to use `getTime`, but that doesn't make him correct. The only way to "satisfy" the OP's (impossible) desires is to do this. Yes, it will freeze your browser, but that's what you get for (some reason) not wanting to use `setTimeout`. – gen_Eric Mar 16 '12 at 14:20
  • 1
    @jbabey The reason I added the comment was to point out that you should edit your answer to reflect that point. People that starts with JavaScript don't always understand that this would just freeze the browser. – HoLyVieR Mar 16 '12 at 14:24
2

You do something like this

// place you code in this function 
(async function main(){

    //Do something
    console.log("something Done first ")
    // code execution will halt for period (ms)
    await sleep(3000)

    console.log("something Done 3 seconds later ")
    //Do something

})()

function sleep(period) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, period);
    });
}
dferenc
  • 7,918
  • 12
  • 41
  • 49
  • You don't need an async function anymore, since about 2018 before you answered this. Also you don't need a function that calls resolve, you can just call resolve. – s123 Aug 18 '23 at 08:59
2

If you are using jQuery 1.5+ you can make a really simple plugin (i

(function($) {
    $.wait = function(time) {
         return $.Deferred(function(dfd) {
               setTimeout(dfd.resolve, time); // use setTimeout internally. 
         }).promise();
    }
}(jQuery));

Then use it like this:

$.wait(3000).then(function(){ 
   ....
});

And it will launch your function after waiting 3 seconds. It use setTimeout internally, but that's the only way to do it in JavaScript.

Guumaster
  • 389
  • 3
  • 10
1

You can use this code: (stolen from http://www.phpied.com/sleep-in-javascript/)

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

This will actually block the script execution for however many milliseconds you desire. Don't use it unless you are trying to simulate a task that takes a long time, or something like that.

BonsaiOak
  • 27,741
  • 7
  • 30
  • 54
1

we have a npm package called sleep that you can see it here

and for using it simply

var sleep = require('sleep');
sleep.sleep(10) //sleep for 10 seconds

but pay attention to this

These calls will block execution of all JavaScript by halting Node.js' event loop!

if you want sleep with promise you can use then-sleep npm package that is a good choice

  var sleep = require('then-sleep');

// Sleep for 1 second and do something then. 
sleep(1000).then(...);

also if you use ES7 you can use es7-sleep npm package

MBehtemam
  • 7,865
  • 15
  • 66
  • 108
  • This doesn't answer their question, they asked not to have to use callbacks. This is basically the same as setTimeout. Just use await if you're already using promises. – s123 Aug 18 '23 at 09:02
0

if you use node 9.3 or higher you can use Atomics.wait() like this

function msleep(n) {
   Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, n);
  }
function sleep(n) {
    msleep(n*1000);
}

now you can call sleep()

MBehtemam
  • 7,865
  • 15
  • 66
  • 108
0

Promises exist since 2016 and top-level await since 2018 so all the answers are outdated:

function sleep(delayMs){
    return new Promise(resolve => setTimeout(resolve, delayMs))
}

console.log(0)
await sleep(5000)
console.log(1) // 5 seconds later
s123
  • 102
  • 9