让我们考虑一下这样的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") );
});
会发生什么:
extra-class
.my-class
10ms
切换scope
extra-class
添加到某个项目scope
10ms
我正在做一些花费更多时间的行动
比scope
如果我可以肯定 - 这是否意味着即使从最后一个时间间隔过去的时间超过应该等待的时间间隔,我也会等待我的范围完成?如果某个单一范围比间隔时间多100倍会怎么样?
如果我不能确定 - 这是否意味着可以在我的范围代码中间触发间隔操作?
答案 0 :(得分:2)
// (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是单线程的,因此只有一个线程贯穿A
,B
,然后C
。在当前正在执行的代码完成之前,不会执行任何其他JavaScript代码。
即使您已设置setInterval
以便在给定时间执行某个功能,该功能也只会在单个线程空闲时按时运行。否则,它必须等到单个线程完成其他所有操作。