Javascript setTimeout 是否停止其他脚本执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10258012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:12:04  来源:igfitidea点击:

Does Javascript setTimeout stop other script execution

javascript

提问by Umesh Moghariya

I am referring to this. Everything is still not clear.

我指的是这个。一切都还不清楚。

  • I have a JS function fillTree()which updates a tree, it has checkboxes.
  • I have another function checkSelectedBoxes()which is executed on window.onloadwhich checks for selected checkboxes.
  • Now there are lots of other functions connected.
  • 我有一个fillTree()更新树的 JS 函数,它有复选框。
  • 我有另一个checkSelectedBoxes()执行window.onload检查选定复选框的函数。
  • 现在还有很多其他功能连接。

My question:

我的问题:

  • If I am using setTimeout()will the other script function also stop and wait for my function to finish loading?
  • 如果我正在使用setTimeout()其他脚本函数是否也会停止并等待我的函数完成加载?

What might be the case in this:

这可能是什么情况:

function fillTree(){...}
function checkSelectedBoxes(){...}

fillTree(); // This take time to get data. onLoad() doesnt work.
setTimeout(function(){ checkSelectedBoxes()  },5000);

This returns me null values even after increasing the time interval. Does fillTree()pause execution?

即使在增加时间间隔后,这也会返回空值。是否fillTree()暂停执行?

回答by Joseph

No, setTimeoutdoes not wait for you (hence, JS has no pause function). What setTimeoutdoes is set aside that task at a later time, and allow the next line to be executed. when that timeout is reached , it inserts that task into the execution line.and when no other code is running, it executes the function that was indicated.

不,setTimeout不等你(因此,JS 没有暂停功能)。什么setTimeout是稍后搁置该任务,并允许执行下一行。当达到该超时时,它将该任务插入到执行行中。当没有其他代码正在运行时,它会执行所指示的函数。

what you want to do is give a callback to your fillTree()and execute when it's done.

你想要做的是给你一个回调fillTree()并在它完成后执行。

function fillTree(callback){

    //do something very long

    callback(); //execute passed function when it's done
}

fillTree(function(){
    checkSelectedBoxes(); //executes only when fillTree finishes
})

回答by Rory McCrossan

its a CMS i am using and the tree is set in some other js file which I am not to interfere with as it is used many other functions and the cases may not be always same

它是我正在使用的 CMS,并且树设置在其他一些 js 文件中,我不会干扰它,因为它使用了许多其他功能,并且情况可能并不总是相同

If the fillTree()function cannot be modified you can wrap it in your own function and apply a callback function to that. Try this:

如果fillTree()无法修改该函数,您可以将其包装在您自己的函数中并对其应用回调函数。试试这个:

function doStuff(callback) {
    fillTree();

    // Call the callback parameter (checkSelectedBoxes() in this case)
    // when fillTree() has completed
    callback();
}

doStuff(checkSelectedBoxes);

回答by loretoparisi

The setTimeoutfunction does not wait execution and you can clearly check it in the following snippet. You can see how, given the array waitTimesof random times, the Array.mapfunction will print out first all the time[index]=waitTimes[index]values, then the wait[index]=waitTimes[index]when the setTimeoutis fired exactly after waitTimes[index]milliseconds.

setTimeout函数不等待执行,您可以在以下代码段中清楚地检查它。你可以看到,给定阵列waitTimes的随机时间,该Array.map功能将打印出首先的time[index]=waitTimes[index]值,那么wait[index]=waitTimes[index]setTimeout在后正好解雇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" />

回答by Dmitry

I just made a test which may be of interest:

我刚刚做了一个可能感兴趣的测试:

<!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>

I'm now really curious how JavaScript knows when certain amount of time has elapsed. Does it spawn a thread that sleeps for a period of time? And if so is there a limit on how many threads sleep, or are sleeping threads "stored" until they are needed? Much confuse.

我现在真的很好奇 JavaScript 如何知道何时已经过去了。它会产生一个休眠一段时间的线程吗?如果是这样,睡眠线程的数量是否有限制,或者是否“存储”了睡眠线程直到需要它们?很混乱。

I think it has something to do with

我认为这与

"If it doesn't need to be exactly 1s, then just usleep a second. usleep and sleep put the current thread into an efficient wait state that is at least the amount of time you requested (and then it becomes eligible for being scheduled again).

If you aren't trying to get near exact time there's no need to check clock()."

“如果它不需要正好是 1s,那么只需 usleep 一秒钟。usleep 和 sleep 将当前线程置于有效的等待状态,该状态至少是您请求的时间(然后它有资格再次被调度)。

如果您不想接近准确时间,则无需检查clock()。”

--pthread sleep function, cpu consumption

-- pthread sleep函数,cpu消耗

So I guess the operating system does the scheduling for you, at which point it interrupts the engine, and the engine stops the world and puts the timeout function on top of the queue to be executed as soon as possible?

所以我猜操作系统为你做了调度,在这一点上它中断引擎,引擎停止世界并将超时函数放在队列的顶部以尽快执行?