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

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


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 );

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