Syncronous execution与setTimeout()执行顺序异常问题求助
Hey there! Let's break down why your code isn't behaving as expected and get it sorted out.
Why Your Current Code Acts That Way
JavaScript runs on a single thread, and it always executes synchronous code first before handling asynchronous tasks like setTimeout callbacks. Here's the play-by-play of what's happening with your code:
- It immediately prints
1and2(these are synchronous console logs). - It schedules the first
setTimeoutcallback (to print3) to run after 2 seconds, then moves right along. - It immediately prints
4(another synchronous log that doesn't wait for anything). - It schedules the second
setTimeoutcallback (to print5) to run after 2 seconds. - After 2 seconds, both scheduled callbacks fire one after another, so you see
3and5pop up almost simultaneously.
That's why you end up with 1, 2, 4 → (wait 2s) → 3, 5 instead of the sequence you wanted.
Solutions to Get Your Desired Output
If your goal is 1, 2 → (wait 2s) → 3, 4 → (wait 2s) → 5, here are two solid ways to make that happen:
1. Nested setTimeout Calls
This is the classic approach for sequential asynchronous tasks:
console.log("1"); console.log("2"); setTimeout(function() { // Runs after the first 2-second wait console.log("3"); console.log("4"); // Schedule the next delay only after the first callback finishes setTimeout(function() { console.log("5"); }, 2000); }, 2000);
By nesting the second timeout inside the first callback, we ensure the 2-second wait happens after 3 and 4 are printed, not before.
2. Using async/await (More Readable)
For cleaner, easier-to-follow code, wrap the delay in a Promise and use async/await:
// Helper function to create a delay using a Promise function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function runSequence() { console.log("1"); console.log("2"); await delay(2000); // Wait 2 seconds console.log("3"); console.log("4"); await delay(2000); // Wait another 2 seconds console.log("5"); } runSequence();
async/await lets you write asynchronous code that reads like synchronous code, so the sequence of actions is immediately clear.
内容的提问来源于stack exchange,提问作者Clone

