Sometimes as a programmer you get into a situation in which the execution of the program should be interrupted for a short time. To do this, there are various options in the various programming languages. In JavaScript since ES6 there has been an option to use Promises for this purpose.
Implement a sleep function
In order to pause a few seconds in JavaScript, it is sufficient to define a small auxiliary function. The Sleep function returns a promise object , the status of which is set to resolved after the desired time in milliseconds .
function Sleep(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
If you would like to use this functionality now, you must mark your function with the async keyword. Without async , you are not allowed to use the await command . An exemplary application shows the following function: The function calls the sleep function. Using await , the function stops executing for the specified time. Without
async function test() {
console.log("Vor der sleep-Funktion");
await Sleep(3000); // Pausiert die Funktion für 3 Sekunden
console.log("Nach der Sleep Funktion");
}
await , the function would continue to run because it is not waiting for the Promise object returned by Sleep to resolve.
Perform a function with a delay
To execute a function after a certain waiting time, there is the function setTimeout . With setTimeout , a so-called callback function is passed to be executed. This function is carried out after the specified time. So define a function that is to be called: Now you can use setTimeout to call the function you just created with the specified delay. It should be noted, however, that the following code is executed without waiting time: Alternatively, it is also possible to pass a function expression as an argument for setTimeout . You can also call setTimeout as follows:
function callback() {
console.log("Callback Funktion wird aufgerufen");
}
setTimeout(callback, 3000); //Ruft die Callback-Funktion nach 3 Sekunden auf
console.log("Test"); //Wird sofort, ohne Wartezeit ausgeführt
setTimeout(function() {
console.log("Callback Funktion wird aufgerufen");
}, 3000);
The advantage here is that no new function has to be defined and you can immediately see which code block will be executed after the delay.