請寫一個sleep(暫停)函式

王铁柱6發表於2024-11-24
/**
 * Pauses execution for a specified number of milliseconds.
 *
 * @param {number} ms The number of milliseconds to pause for.
 * @returns {Promise<void>} A Promise that resolves after the specified delay.
 */
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}


// Example usage:

async function demo() {
  console.log("Starting demo...");
  await sleep(2000); // Pause for 2 seconds
  console.log("Two seconds later...");
}

demo();


// Another example using async/await and showing a loading message:

async function fetchData() {
  console.log("Fetching data...");
  // Simulate an API call that takes some time
  await sleep(3000);
  console.log("Data fetched!");
  return "Some data";
}

async function displayData() {
  const loadingMessage = document.createElement('p');
  loadingMessage.textContent = 'Loading...';
  document.body.appendChild(loadingMessage);


  const data = await fetchData();
  console.log(data); // Log the fetched data

  document.body.removeChild(loadingMessage); // Remove the loading message

  const dataDisplay = document.createElement('p');
  dataDisplay.textContent = data;
  document.body.appendChild(dataDisplay);
}



displayData();

Explanation:

  1. Promise based: The sleep function uses a Promise to handle the asynchronous delay. This is the standard way to handle asynchronous operations in JavaScript and allows you to use async/await for cleaner code.

  2. setTimeout: Inside the Promise, setTimeout is used to schedule the execution of the resolve function after the specified ms (milliseconds) delay.

  3. async/await: The examples demonstrate how to use async/await to call the sleep function. The await keyword pauses the execution of the async function until the Promise returned by sleep resolves (after the delay). This makes asynchronous code look and behave a bit more like synchronous code, which is easier to read and understand.

  4. Example with loading message: The second example shows a more practical use case, simulating fetching data from an API. It includes a loading message to inform the user that the operation is in progress, improving the user experience. This example also demonstrates how to manipulate the DOM (add and remove elements) in conjunction with the sleep function.

This approach is widely used and preferred over older methods (like using setTimeout directly for pausing execution flow) because it's more manageable and integrates well with modern JavaScript's asynchronous programming paradigms.

相關文章