How to make a non-blocking sleep in javascript/jquery?
3 Answers
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 );
Comments
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".
setTimeout()?var halt=+new Date+3000;while(1){if(new Date>halt)break;}console.log('done after blocking for 3 seconds')pausecomp(millis) { var date = new Date(); var curDate = null; do { curDate = new Date(); } while(curDate-date < millis); }As for non-blocking obviouslysetTimeout()