简体   繁体   English

即使使用setTimeout,循环也总是结束

[英]Loop always finishes, even with setTimeout

I am running some JavaScript code to test/understand the behaviour of setTimeOut. 我正在运行一些JavaScript代码来测试/理解setTimeOut的行为。

I use this code: 我使用以下代码:

var timerx1 ;

if (timerx1) window.clearTimeout(timerx1);
timerx1 = setTimeout(testme, 10);

To call this function: 调用此函数:

function testme() {
    for (var c = 0; c < 900000; c++) {
        document.getElementById("divMode").innerHTML = c;
    } 
}

This loop will always finish before exiting. 该循环将始终在退出之前完成。

I had expected that the setTimeOut of 10ms would 'kick' in and the loop aborted before completion. 我曾期望setTimeOut为10ms会“踢”进去,并且循环在完成之前会中止。

I stress this is not part of any other code or application. 我强调这不是任何其他代码或应用程序的一部分。 I am just trying to understand how setTiemOut works and any limitations. 我只是想了解setTiemOut的工作原理和任何限制。

setTimeout doesn't interrupt or "timeout" your loop: it merely calls the callback function after so much time has passed. setTimeout不会中断或“超时”循环:它只是在经过了很多时间后才调用回调函数。

Calls a function or executes a code snippet after a specified delay. 在指定的延迟后调用函数或执行代码段。

setTimeout等待指定的毫秒数并执行函数。在您的示例中,您等待10ms

Javascript runs tasks on a stack. Javascript在堆栈上运行任务。 Your for loop executes completely as one of those loops. 您的for循环完全作为这些循环之一执行。 When you use a setTimeout it takes the function you passed in and appends it to the end of that task stack. 当您使用setTimeout它将采用您传入的函数并将其附加到该任务堆栈的末尾。 Then it will execute that task when appropriate. 然后它将在适当的时候执行该任务。

                              // current thread  | waiting
doSomething();                //   execute now   |    --
setTimeout(doSomething, 10);  // append to stack | doSomething (8ms left)
doSomethingElse();            //   execute now   | doSomething (5ms left)
// End of current thread      //      --         | doSomething (0ms left) do this next
                              //    doSomething  |    --

SetTimeout returns immediately as if it was finished. SetTimeout立即返回,就好像它完成了一样。 It basically assigns the function to a pending state and will be executed after the current thread is finished (current function is over/returned) and the timeout timer is finished. 它基本上分配功能挂起状态和当前线程完成之后将被执行(上方/返回当前函数) 超时定时器结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM