我不明白javascript中的setTimeout(fn,0)是如何工作的 [英] Idont understand how setTimeout(fn,0) in javascript works

查看:70
本文介绍了我不明白javascript中的setTimeout(fn,0)是如何工作的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解为什么下面的代码没有按照我的预期行事时遇到了问题。我希望它能够:

I'm having problems understanding why code below doesn't behave as I would expect it to. I would expect it to:


  1. 以黄色边框显示aaa,

  2. 然后阻止UI时间( 循环)

  3. 然后在粉色边框中显示无

  1. display aaa in yellow border,
  2. then block UI for short time (for loop)
  3. then display "nothing" in pink border

当我用setTimeout(aaa,100)替换setTimeout(aaa,0)时,它每次都能正常工作但不应该将setTimeout(aaa,0)放入队列中并使用我的aaa函数允许浏览器在运行aa之前进行重绘?我希望它每次都遵循步骤1-3,但显然我错过了一些东西。它似乎每隔一秒运行一次。

When I replace setTimeout(aaa,0) with setTimeout(aaa,100) it works fine every time but shouldn't the setTimeout(aaa,0) put my aaa function in the queue and allow browser to do the redraw before aa is run? Iwould expect it to follow steps 1-3 every time yet obviously I'm missing something. It seems to behave this way every second run only.

代码在下面,我在 http:/创建小提琴/jsfiddle.net/dDJ8L/

HTML

<div id="aaa" style="border: 1px solid green">aaa</div>

Javascript

Javascript

div = document.getElementById("aaa");

div.style.border = "1px solid red";


function aaa() {

    for (var i = 0; i < 1000000; i++) {
        div.innerHTML = i;
    }
    div.innerHTML = "nothing";
    div.style.border = "1px solid pink";
}

div.style.border = "1px solid blue";
setTimeout(aaa, 0);
div.style.border = "1px solid yellow";


推荐答案

.setTimeout()将其放入队列中结束。它在边框设置为黄色后运行,因此呈现粉红色。

.setTimeout() puts it in the queue at the end. It is running after the border is set to yellow so it comes up as pink.

这篇关于我不明白javascript中的setTimeout(fn,0)是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆