Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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 wait for the specified millisecond and the execute the function.. In your example you are waiting 10ms

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top