Paw*_*weł 5 javascript settimeout
var timeout = setTimeout(function(){
     console.log("I'm message from timeout");
},0);
console.log("I'm message from outside timeout");
//1. I'm message from outside timeout
//2. I'm message from timeout
Run Code Online (Sandbox Code Playgroud)
尽管将setTimeout时间设置为0,为什么内部指令不会先执行?我使用各种时间,包括0/null,我想知道如何保留setTimeout对象并使用流程执行其指令.
Javascript代码仅在一个线程上运行.setTimeout安排一个稍后运行的功能.所以在js中当所有当前运行的代码完成其执行时,event循环将查找任何其他事件.因此,setTimeout( .. 0)将使代码在当前循环之后运行.
console.log("I'm message from outside timeout");将首先安排执行.一旦完成,setTimeout将执行
所以底线setTimeout(myfunction ,0)将在当前执行函数后运行myms 0ms.在你的情况下,当前的执行循环是
console.log("I'm message from outside timeout");
Run Code Online (Sandbox Code Playgroud)
如果你添加另一个console.log("我是来自timeout1外部的消息"); 所以当前事件循环将首先记录
I'm message from outside timeout
I'm message from outside timeout1
Run Code Online (Sandbox Code Playgroud)
在开始setTimeout功能之前   .
注意 setTimeout最小超时为4毫秒.您可以查看此Stackoverflow线程以了解有关它的更多信息
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           1458 次  |  
        
|   最近记录:  |