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

6
  • 3
    The programming model in JavaScript in general is non-blocking, so you wont have any blocking call like a sleep() function. Commented Mar 16, 2012 at 14:09
  • 1
    No --- See also this maybe duplicate thread Commented Mar 16, 2012 at 14:09
  • Why don't you want to use setTimeout? Commented Mar 16, 2012 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) Commented Mar 16, 2012 at 14:13
  • Check out this thread: stackoverflow.com/questions/5832276/… Commented Mar 16, 2012 at 14:13

8 Answers 8

20

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.

Sign up to request clarification or add additional context in comments.

Comments

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 

5 Comments

I was just writing something similar.
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 the OP stated he wanted to "pause the script" - if you pause javascript, you're blocking the browser. period.
@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.
@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.
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.

2 Comments

Or setTimeout(func, 3000) (which is what is happening anyway)?
That's the exact same thing as setTimeout.
2

You do something like this

`

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); (async function main() { //Do something console.log("something Done first "); // function execution will halt for period (ms) await sleep(3000); console.log("something Done 3 seconds later "); //Do something })(); 

`

1 Comment

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

1 Comment

this is missed up!
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

1 Comment

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

2 Comments

Thanks, now the Python developers that have come on to my Javascript project are locking up the whole thread.
Promises have existed since 2016 so this answer is incorrect.
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.