HTML and CSS Reference
In-Depth Information
If you execute this you should see the execution begin after approximately 5 seconds.
JavaScript executes this by encapsulated the function call in an event and adding that event
to the event queue after 5 seconds. It will only execute when it gets to the front of the event
Before performing a long running calculation, it is sometimes useful to yield control back
to the browser to ensure any other events that are waiting can be processed (particularly
user driven events) first, and therefore stops the application from appearing to “lock-up”.
Your processing can be encapsulated in a call to setTimeout with a very small delay (10
milliseconds for instance). This will guarantee that you go to the back of the event queue
(and any pending events will occur), but still will not result in any unnecessary delay if
there are no other events waiting to run.
The setTimeout function can also be used to yield control back to the browser during a
long running task. If you were to perform a computation that took 10 seconds, by default
you would not be interrupted during this period, so all other events would queue up behind
you. Instead, if there is a way of breaking the computation up, you can choose a point where
you wish to yield, and ask the next portion of the algorithm to run by calling setTimeout
with a delay of 10 milliseconds.
If this was done every 100 milliseconds, it is unlikely the user would notice that there was
a long running computational process executing on the same thread.
The main challenge in achieving this is pausing and resuming the computation. It will typ-
ically be necessary to store the current state of the algorithm, and pass this to the function
that will continue the processing.
setTimeout has a companion function called setInterval . Unlike setTimeout which causes
a function to be executed once, setInterval causes a function to be executed indefinitely
with a given delay between executions. The following is a simple example:
> setInterval(function() {
console.log('hello world');
}, 1000)
This will cause “hello world” to be printed to the console every second indefinitely. setIn-
terval is very useful for implementing background jobs that need to perform operations
As with setTimeout , setInterval generates events that are placed on the event queue.
Therefore they can only run once they get to the front of the event queue.
Search WWH ::

Custom Search