Js实现sleep

59 阅读1分钟

In JavaScript, there is no built-in sleep function like in some other programming languages. However, you can achieve a similar effect using setTimeout or setInterval functions.

Here's an example using setTimeout to create a sleep-like behavior in a loop:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function myFunction() {
  while (true) {
    console.log("Sleeping...");
    await sleep(1000); // Sleep for 1 second (1000 milliseconds)
    console.log("Awake!");
  }
}

myFunction();

In this example, the sleep function returns a promise that resolves after the specified number of milliseconds. The await sleep(1000) line pauses the execution of the loop for 1 second. You can adjust the sleep duration as needed.

Note that running an infinite loop like this with while (true) may cause your program to become unresponsive. It's generally a good idea to have a way to break out of the loop or add some condition to stop the execution.