是否“setTimeout(functon(){// do stuff},0)"导致它包含的函数导致一个微小的执行延迟? [英] Does "setTimeout(functon(){//do stuff},0)" cause a minuscule execution delay for it's contained function?

查看:116
本文介绍了是否“setTimeout(functon(){// do stuff},0)"导致它包含的函数导致一个微小的执行延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我出于好奇而设置了一个简单的实验:

I set up an simple experiment out of curiosity:


  • 我用类<$ c $动态生成一个div c> box 在用JQuery附加点击监听器之前。

  • I dynamically generated a div with the class box before attaching a click listener to it with JQuery.

然后我创建了一个副本,除了这次,在生成元素之前,我添加了超时零。

I then created a duplicate of this, except this time, I added a timeout of zero before the box element is generated.

如JSFiddle所示,使用超时为零会导致点击失败要触发的结果事件。

As shown in the JSFiddle, using a timeout of zero results in the failure of the click's intended result event to be triggered.

此脚本会在点击时产生警告。

This script results in an alert on click.

$(document).ready(function(){

    //setTimeout(function(){
        $(".wrapper").html('<div class="box"></div>');
    //},0)

    $(".box").click(function(){
        console.log("A box was clicked!");
    });

});

此脚本没有。

$(document).ready(function(){

    setTimeout(function(){
        $(".wrapper").html('<div class="box"></div>');
    },0)

    $(".box").click(function(){
        console.log("A box was clicked!");
    });

});

为什么超时为零会导致元素(我假设)在click事件监听器之后生成通过JQuery附加?

Why does a timeout of zero cause the element to be (I assume) generated after the click event listener is attached via JQuery?

setTimeout(functon(){// do stuff},0)导致执行极小延迟它的包含函数?如果是这样,为什么会发生这种情况?

Does setTimeout(functon(){//do stuff},0) cause a minuscule execution delay for it's contained function? If so, why does this happen?

推荐答案

JavaScript是单线程和事件基。 setTimeout()立即创建一个需要处理的新事件,但必须首先完成当前的事件(函数/代码)。

JavaScript is singled-threaded and event-based. setTimeout() immediately creates a new event that needs to be processed, but the current "event" (function/code) must be finished, first.

摘自事件和时间深度


当setTimeout得到0作为最后一个参数时,它会尝试尽快执行
func。

When setTimeout gets 0 as the last argument, it attempts to execute the func as soon as possible.

执行func会转到最近的计时器
tick上的Event队列。请注意,这不是立即的。在
下一个刻度之前不会执行任何操作。

The execution of func goes to the Event queue on the nearest timer tick. Note, that’s not immediately. No actions are performed until the next tick.

其他详细说明:

  • How JavaScript Timers Work
  • Effect of Setting setTimeout to 0 and Explanation of JavaScript's Single Threaded, Non Blocking I/O, Async Event Driven Model

注意:我经常使用这个 setTimeout(func,0)技巧来执行必须在DOM操作或当前函数完成后运行的代码。

Note: I often use this setTimeout(func, 0) "trick" to execute code that must be run after a DOM manipulation or the current function is completed.

这篇关于是否“setTimeout(functon(){// do stuff},0)&quot;导致它包含的函数导致一个微小的执行延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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