Delay function in JavaScript JS

The timeout function puts a thread to sleep, which is often NOT what you want:

function someFunction(param) {
    setTimeout(function () {
        if (param == -1) {
            console.log('Parameter is -1');
        }
    }, 2000);//2 sec delay
}

Instead with ECMA6 you can use the async/await syntax.

const delay = ms => new Promise(res => setTimeout(res, ms));

const delayFunction = async () => {
  await delay(2000);
  console.log("[X] 2 sec delay.");
};

The Code looks like being synchronous while it is in fact asynchronous. This makes it easier to maintain. Plus you avoid a freeze in UIs in case you want to delay for the human eye in a UI…

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.