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.- To interrupt the execution of JavaScript in this way for some time, you must first define a helper function.
- This helper function returns a Promis object and is set back to resolved after the defined time.
- 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.
- 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.