setTimeout/setInterval伪异步

setTimeout(function(){alert(1);}, 1000);

在使用setTimeout、setInterval的时候,会传一个时间来控制代码的执行时机。在经过了设置的时间段后,代码开始执行。这看上去很像是在异步执行。

但是,如果在执行队列中之前的代码执行了超过设置的时间时,例如

function test(){

  setTimeout(function(){alert(1);}, 1000);

  while(true){}

}

此时,由于while执行的时间一定会超过1s,所以alert并不会按照预期在1s之后出现。

原文地址:https://www.cnblogs.com/charling/p/3416899.html