HOME > System software > Javascript: Sleep And Settimeout - How To Apply The Functions

JavaScript: Sleep and setTimeout - how to apply the functions

In JavaScript, there are two functions, sleep and setTimeout, that you can use to briefly interrupt or delay the execution of your programs. In this article, we will show you step by step how to define the two functions correctly.

SetTimeout: How to implement a sleep function in JavaScript

When you use JavaScript for programming, there is no direct function to interrupt the execution of the program. Nevertheless, JavaScript provides you with several methods to implement a sleep function. One way is to use Promises.
  1. To interrupt the execution of JavaScript in this way for some time, you must first define a helper function.
  2. This helper function returns a Promis object and is set back to resolved after the defined time.
  3. To do this, enter the command "function Sleep (milliseconds) {return new Promise(resolve => setTimeout(resolve, milliseconds)); }" and replace the placeholder "milliseconds" thereby with the desired time the script should pause.
  4. In order to subsequently use the previously defined sleep function in your program, it is important to mark it with the "async" command and call it with the "await" command, as this is the only way to pause the function execution.

How to apply the setTimeout function in JavaScript

Another way to execute a function with delay in JavaScript is to use the "setTimeout" function. To use this method, you can either define a new function or use a function expression as an argument to setTimeout. Um letztere Variante ohne Neudefinition zu nutzen, geben Sie bitte den folgenden Befehl ein: „setTimeout(function() {console.log("Callback Funktion wird aufgerufen"); }, 3000);“.

By Sankaran Farrauto

My Time at Portia: How to get upgrade sets :: Google Chrome: Install apps - how to do it
USEFUL LINKS