javascript setInterval 和 setTimeout 'threads' 是如何工作的?

How does javascript setInterval and setTimeout 'threads' works?

让我们考虑一下 html:

<div class="my-class"></div>

和 js(使用 jQuery):

var interval = 10;

setInterval(function(){
    //I toggle .my-class 'extra-class' every 10ms
    $(".my-class").toggleClass("extra-class"); 
}, interval);

//then outside interval I'm doing some action on the same item as interval does
$(".my-class").each(function(){
    var t = $(this).addClass("extra-class"); //I'm sure I've added extra-class

    //but now I'm doing some action longer than 10ms
    for (var i = 0; i < 10000; i++) {
        //some long action here that could take more than 10ms
    };

    //can I still be sure now that it have extra-class added in THIS scope
    //it was added in this scope but it is toggled all the time
    console.log( t.hasClass("extra-class") ); 
});

发生的事情是:


如果我可以确定 - 这是否意味着间隔正在等待我的范围完成,即使从上一个间隔开始的时间比它应该等待的时间要多?如果某个单一示波器花费的时间是间隔时间的 100 倍怎么办?

如果我不能确定 - 这是否意味着可以在我的范围代码中间触发间隔操作?

// (A)
var t = $(this).addClass("extra-class"); //I'm sure I've added extra-class

// (B)
// Some long action here that could take more than 10ms
...

// (C)
// can I still be sure now that "this" still has class "extra-class"?

是的。由于 JavasScript 是单线程的,因此只有一个线程 运行 通过 AB 然后 C。在当前执行的代码完成之前,不会执行其他 JavaScript 代码。

即使您设置了 setInterval 以便在给定时间执行函数,如果单个线程空闲,该函数也只会按时 运行。否则,它将不得不等到单线程执行完其他所有内容。