13

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

8
  • 6
    You mean like a timeout? Commented Oct 11, 2011 at 16:32
  • 3
    How do you make a blocking sleep in javascript? Commented Oct 11, 2011 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()? Commented Oct 11, 2011 at 16:36
  • @Dykam, var halt=+new Date+3000;while(1){if(new Date>halt)break;}console.log('done after blocking for 3 seconds') Commented Oct 11, 2011 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() Commented Oct 11, 2011 at 16:39

3 Answers 3

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 );
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0

Inside Node, without using new Promise() explicity

      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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.