[英]Does Javascript setTimeout stop other script execution
我指的是这个 。 一切都还不清楚。
fillTree()
更新树,它有复选框。 checkSelectedBoxes()
,它在window.onload
上执行,它检查所选的复选框。 我的问题:
setTimeout()
,其他脚本函数是否也会停止并等待我的函数完成加载? 可能是这种情况:
function fillTree(){...}
function checkSelectedBoxes(){...}
fillTree(); // This take time to get data. onLoad() doesnt work.
setTimeout(function(){ checkSelectedBoxes() },5000);
即使在增加时间间隔后,这也会返回空值。 fillTree()
暂停执行吗?
不, setTimeout
不会等你(因此,JS没有暂停功能)。 setTimeout
执行的操作是稍后将该任务放在一边,并允许执行下一行。 达到超时时,它会将该任务插入执行行。 当没有其他代码在运行时,它会执行指示的功能。
你想要做的是给你的fillTree()
回调并在完成后执行。
function fillTree(callback){
//do something very long
callback(); //execute passed function when it's done
}
fillTree(function(){
checkSelectedBoxes(); //executes only when fillTree finishes
})
它是我正在使用的CMS,并且树被设置在一些其他js文件中,我不会干涉,因为它使用了许多其他功能,并且情况可能并不总是相同
如果无法修改fillTree()
函数,可以将其包装在自己的函数中并对其应用回调函数。 尝试这个:
function doStuff(callback) {
fillTree();
// Call the callback parameter (checkSelectedBoxes() in this case)
// when fillTree() has completed
callback();
}
doStuff(checkSelectedBoxes);
setTimeout
函数不会等待执行,您可以在下面的代码片段中清楚地检查它。 您可以看到,给定随机时间的数组waitTimes
, Array.map
函数将Array.map
首先打印出time[index]=waitTimes[index]
值,然后在setTimeout
time[index]=waitTimes[index]
wait[index]=waitTimes[index]
在waitTimes[index]
毫秒之后完全触发。
var console = { log: function(s) { document.getElementById("console").innerHTML += s + "<br/>" } } var roundDecimals = function(num, pos) { pos = pos || 4; return (Math.round(num * Math.pow(10, pos)) / Math.pow(10, pos)); } var arrayRangeMap = function(a, block) { c = []; while (a--) c[a] = block(); return c }; var getRandomArbitrary = function(min, max) { return (Math.random() * (max - min) + min); } // random 10 wait times, 3 decimal positions var waitTimes = arrayRangeMap(10, function() { return roundDecimals(getRandomArbitrary(0.250, 0.5, 3) * 1000, 2); }); waitTimes.map(function(item, index) { setTimeout(function() { console.log("wait[" + index + "]=" + item); }, item); console.log("time[" + index + "]=" + item); });
<div id="console" />
我刚做了一个可能感兴趣的测试:
<!DOCTYPE html>
<html>
<head>
<script>
/* test: if returns in around 1000ms, must interrupt, otherwise it is indeed
not going to let timeout work until work is done. */
window.onload = function() {
var before = performance.now();
setTimeout(function() {
alert('completed in ~' + (performance.now() - before) + ' nanoseconds.');
}, 1000);
/* count to 2^31 - 1... takes 8 seconds on my computer */
for (var i = 0; i < 0xffffffff; ++i) {
/* me busy, leave me alone */
}
};
</script>
</head>
<body>
</body>
</html>
我现在真的很好奇JavaScript知道什么时候已经过去了。 它会产生一段睡眠一段时间的线程吗? 如果是这样,是否有多少线程睡眠,或者睡眠线程“存储”直到需要它们? 很混乱。
我认为这与某些事情有关
“如果它不需要精确到1秒,那么只需要睡一秒钟。睡眠和睡眠使当前线程进入一个有效的等待状态,至少是您请求的时间量(然后它就有资格再次安排) )。
如果你不想接近准确的时间,就不需要检查时钟()。“
所以我想操作系统会为你做调度,此时它会中断引擎,引擎会停止这个世界并将超时功能置于队列之上,以便尽快执行?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.