12

How to make a non-blocking sleep in javascript/jquery?

royhowie
  • 11,075
  • 14
  • 50
  • 67
aF.
  • 64,980
  • 43
  • 135
  • 198
  • 6
    You mean like a [timeout?](https://developer.mozilla.org/en/window.setTimeout) – Pekka Oct 11 '11 at 16:32
  • 3
    How do you make a blocking sleep in javascript? – Dykam Oct 11 '11 at 16:33
  • 1
    @aF - you're going to need more detail about what you want before you can get a useful response. Are you looking for anything other than `setTimeout()`? – nrabinowitz Oct 11 '11 at 16:36
  • @Dykam, `var halt=+new Date+3000;while(1){if(new Date>halt)break;}console.log('done after blocking for 3 seconds')` – davin Oct 11 '11 at 16:39
  • 1
    Yeah, blocking sleep can be done. For example function `pausecomp(millis) { var date = new Date(); var curDate = null; do { curDate = new Date(); } while(curDate-date < millis); }` As for non-blocking obviously `setTimeout()` – freakish Oct 11 '11 at 16:39
  • @davin, those are spin loops. Those aren't sleeps, just waits. Sleeps don't keep the CPU busy. The opposite really. – Dykam Oct 11 '11 at 16:41
  • There is no non-blocking sleep in javascript. There are spin loops (eeck, horrible) and there are timeouts. Those are the two options. – jfriend00 Oct 11 '11 at 18:05
  • what I wanted is exactly what Lucas answered! – aF. Oct 12 '11 at 08:28

3 Answers3

20

At the risk of stealing the answer from your commentors, use setTimeout(). For example:

var aWhile = 5000; // 5 seconds
var doSomethingAfterAWhile = function() {
  // do something
}
setTimeout( doSomethingAfterAWhile, aWhile );
David
  • 3,166
  • 2
  • 30
  • 51
Lucas
  • 14,227
  • 9
  • 74
  • 124
1

since ECMAScript 2017 you can benefit from async/await:

https://jsfiddle.net/2tavp61e/

function delay (miliseconds) {
    return new Promise((resolve) => {
        window.setTimeout(() => {
            resolve();
        }, miliseconds);
    });
}

(async function () {
    console.log('A');
    await delay(2000);
    console.log('B');
})();

console.log('C');

"A" appears in the console first, "C" comes immediately after - which is proof that delay is non-blocking, and finally after two seconds there comes "B".

hejdav
  • 1,267
  • 15
  • 19
0

this even works inside async function

      const util = require("util");
      const sleep = util.promisify(setTimeout);
      await sleep(5000); // waiting 5 seconds
      // now send response
      await res.status(401).send("incorrect username or password");
      return;
Firoj Siddiki
  • 1,649
  • 1
  • 20
  • 22