/**
* 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:
-
Promise
based: Thesleep
function uses aPromise
to handle the asynchronous delay. This is the standard way to handle asynchronous operations in JavaScript and allows you to useasync/await
for cleaner code. -
setTimeout
: Inside thePromise
,setTimeout
is used to schedule the execution of theresolve
function after the specifiedms
(milliseconds) delay. -
async/await
: The examples demonstrate how to useasync/await
to call thesleep
function. Theawait
keyword pauses the execution of theasync
function until thePromise
returned bysleep
resolves (after the delay). This makes asynchronous code look and behave a bit more like synchronous code, which is easier to read and understand. -
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.