clocklaha.blogg.se

Javascript sleep 2 seconds
Javascript sleep 2 seconds













javascript sleep 2 seconds

Using setInterval()Īlternatively, you can use the setInterval() function to create a sleep function in JavaScript. This means that you need to define your function as async as well. Note that the sleep() function returns a Promise, so you need to use await when calling it. In the example above, mySleepFunction() logs "start" to the console, waits for 2 seconds using the sleep() function, and then logs "end" to the console. You can then use this sleep() function in your code like this: The function returns a Promise that resolves after the specified time has elapsed. In the example above, sleep() takes an argument ms that specifies the time to wait in milliseconds. Return new Promise(resolve => setTimeout(resolve, ms)) The function will execute after the specified delay time has passed.įollowing is an example of how to use setTimeout() to create a sleep function in JavaScript: SetTimeout() is a method that takes two arguments: a function to be executed and a delay time in milliseconds.

javascript sleep 2 seconds

However, you can achieve a similar effect by using the setTimeout(), setInterval() or Date.now() functions. In JavaScript, the sleep() function is not a built-in function. What is the JavaScript alternative to the sleep function















Javascript sleep 2 seconds