请写一个sleep(暂停)函数
/**
* 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:
-
Promisebased: Thesleepfunction uses aPromiseto handle the asynchronous delay. This is the standard way to handle asynchronous operations in JavaScript and allows you to useasync/awaitfor cleaner code. -
setTimeout: Inside thePromise,setTimeoutis used to schedule the execution of theresolvefunction after the specifiedms(milliseconds) delay. -
async/await: The examples demonstrate how to useasync/awaitto call thesleepfunction. Theawaitkeyword pauses the execution of theasyncfunction until thePromisereturned bysleepresolves (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
sleepfunction.
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.
浙公网安备 33010602011771号