HTML and CSS Reference
In-Depth Information
Threading
Unlike most languages, JavaScript does not offer programmers an approach for utilizing
multiple threads.
Within the browser environment, all JavaScript code executes on a single thread, and this is
also the thread that the browser utilizes to update the window. This means that if you make
changes to the DOM, and then continue to utilize the thread to perform any computation,
your DOM changes will not be applied until you finish this processing.
Browsers do allow documents in different tabs to utilize different threads: this is possible
because the tabs do not interact with one another.
The browser manages the single thread with an event queue. Each time an event occurs, be
it a browser initiated event such as resizing the window, a user initiated even such as click-
ing a button, or a JavaScript initiated event such as a timer executing a function, the event is
added to a queue. The browser then processes these events sequentially and does not begin
processing a new event until all the events ahead of it have finished processing.
This threading model can cause issues, since it does not prioritize the processing of events
based on their source. In real-world applications it is often more important to respond to user
based events quickly, even if that means temporarily interrupting a computational process
currently executing.
HTML5 has addressed this issue to a degree with an API called Web Workers. These will be
introduced later in the topic, but they are not a general purpose solution to threading issues,
since they contain numerous limitations.
JavaScript does provide a mechanism to alleviate some of the issues inherent in the single
thread model with the setTimeout function defined in the language. The setTimeout func-
tion allows code to execute at a delayed interval.
In order to see setTimeout in action, we will first define a function that we wish to execute
at a delayed interval:
> writer = function() {
for (var i = 0; i < 10; i++) {
console.log('Row '+i);
}
}
Next we will ask the browser thread to execute this with a delay of 5000 milliseconds:
> setTimeout(writer, 5000)
Search WWH ::




Custom Search