You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Syncronous execution与setTimeout()执行顺序异常问题求助

Fixing Your JavaScript Execution Order Issue

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:

  1. It immediately prints 1 and 2 (these are synchronous console logs).
  2. It schedules the first setTimeout callback (to print 3) to run after 2 seconds, then moves right along.
  3. It immediately prints 4 (another synchronous log that doesn't wait for anything).
  4. It schedules the second setTimeout callback (to print 5) to run after 2 seconds.
  5. After 2 seconds, both scheduled callbacks fire one after another, so you see 3 and 5 pop 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:07:47