Reputation: 66697
How to make a non-blocking sleep in javascript/jquery?
Upvotes: 13
Views: 12003
Reputation: 1941
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;
Upvotes: 0
Reputation: 1367
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".
Upvotes: 3
Reputation: 14959
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 );
Upvotes: 20