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

如何在递归函数内部即时添加DOM元素?

How to Show Real-Time Execution Progress of a Recursive Function in the Browser

Great question! The core issue here is how browsers handle JavaScript execution and rendering in their single-threaded event loop. When you run your recursive function synchronously, all the DOM updates get queued up and only processed once the entire function finishes executing—so you don't see the numbers appear one by one until the end.

Why Your Current Code Doesn't Work

Browsers prioritize running synchronous JavaScript code first before handling any rendering tasks. Your recursive function runs all 10,000 iterations in a single synchronous block, so the browser can't pause to render each new <p> element until the function completes.

Fix 1: Use setTimeout to Yield Execution to the Browser

By wrapping your recursive call in setTimeout, you're pushing each subsequent iteration into the browser's macro task queue. This gives the browser time to render the current DOM changes before running the next iteration:

let num = 10000;
function recursive() {
  if (num > 0) {
    let p = document.createElement('p');
    p.textContent = num;
    document.body.appendChild(p);
    num--;
    // Yield to the browser by pushing the next call to the macro queue
    setTimeout(recursive, 0);
  }
}
recursive();

The 0ms delay doesn't mean it runs immediately—it just tells the browser to execute the function as soon as it's done with the current tasks (including rendering).

Fix 2: Use requestAnimationFrame for Smoother Rendering

If you want even smoother synchronization with the browser's rendering cycle, use requestAnimationFrame instead. This method schedules your function to run right before the browser's next repaint, making the updates feel more fluid:

let num = 10000;
function recursive() {
  if (num > 0) {
    let p = document.createElement('p');
    p.textContent = num;
    document.body.appendChild(p);
    num--;
    // Sync with the browser's render cycle
    requestAnimationFrame(recursive);
  }
}
recursive();

Bonus: Optimize for Performance

Creating 10,000 separate <p> elements can slow down your page. A better approach is to update a single element's text content instead of creating new ones each time:

let num = 10000;
// Create one element once, then update its content
const progressEl = document.createElement('p');
document.body.appendChild(progressEl);

function recursive() {
  if (num > 0) {
    progressEl.textContent = `Current count: ${num}`;
    num--;
    requestAnimationFrame(recursive);
  } else {
    progressEl.textContent = 'Done! 🎉';
  }
}
recursive();

This reduces DOM clutter and keeps your page responsive even with large numbers of iterations.

Key Takeaway

JavaScript runs on a single thread, so you need to explicitly yield execution to the browser if you want to see real-time updates. Using setTimeout or requestAnimationFrame breaks your synchronous loop into asynchronous chunks, giving the browser time to render changes between iterations.

内容的提问来源于stack exchange,提问作者Imtiaz Kabir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 18:27:49