Java Reference
In-Depth Information
wait("This tape will self-destruct in five seconds ... ",
selfDestruct, 5);
console.log("Hmmm, should I accept this mission or not ...
?");
<< "This tape will self-destruct in five seconds ... "
<< "Hmmm, should I accept this mission or not ... ? "
<< "BOOOOM!"
When the wait() function is invoked, any code inside it is run, so the message " This
tape will self destruct in five seconds ... " is displayed. But
when the setTimeout() function is invoked with a callback, control is handed back to
the program and the next line in the program is run, which displays the message " Hmmm,
should I accept this mission or not ... ? ". After five seconds, the
callback is then called. This demonstrates that the setTimeout() function did not block
the rest of the program from running.
Remember, though, that JavaScript is still single-threaded, so only one task can happen at
once. If an event takes little time to happen, it may still have to wait until other parts of the
program have executed before the callback occurs. For example, let's see what happens if
we set the waiting time to be zero seconds:
wait("This tape will self-destruct immediately ... ",
selfDestruct,
0);
console.log("Hmmm, should I accept this mission or not ...
?");
<< "This tape will self-destruct immediately ... "
<< "Hmmm, should I accept this mission or not ... ?"
<< "BOOOOM!"
Notice the callback in the wait() function is still invoked last, despite the wait time being
set to zero seconds. We would have expected the callback to have been invoked immedi-
ately, but a callback always has to wait for the current execution stack to complete before
it's invoked. In this case, the current execution stack is the rest of the function and and code
already entered in the console. Once these have executed, the callback is invoked before
handing control back to the main program.
Search WWH ::




Custom Search