I am running some JavaScript code to test/understand the behaviour of 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.
I stress this is not part of any other code or application. I am just trying to understand how setTiemOut works and any limitations.
setTimeout doesn't interrupt or "timeout" your loop: it merely calls the callback function after so much time has passed.
Calls a function or executes a code snippet after a specified delay.
setTimeout等待指定的毫秒数并执行函数。在您的示例中,您等待10ms
Javascript runs tasks on a stack. Your for loop executes completely as one of those loops. When you use a setTimeout
it takes the function you passed in and appends it to the end of that task stack. 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.