04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 18: Advanced Techniques<br />

Consider the following code:<br />

var btn = document.getElementById(“my-btn”);<br />

btn.onclick = function(){<br />

setTimeout(function(){<br />

document.getElementById(“message”).style.visibility = “visible”;<br />

}, 250);<br />

};<br />

//other code<br />

Here, an event handler is set up for a button. The event handler sets a timer to be called in 250<br />

milliseconds. When the button is clicked, the onclick event handler is first added to the queue. When it<br />

is executed, the timer is set, and 250 milliseconds later, the specified code is added to the queue for<br />

execution. In effect, the call to setTimeout() says that some code should be executed later.<br />

The most important thing to remember about timers is that the specified interval indicates when the<br />

timer ’ s code will be added to the queue, not when the code will actually be executed. If the onclick<br />

event handler in the previous example took 300 milliseconds to execute, then the timer ’ s code would<br />

execute, at the earliest, 300 milliseconds after the timer was set. All code in the queue must wait until the<br />

JavaScript process is free before it can be executed, regardless of how it was added to the queue. See<br />

Figure 18 - 2 .<br />

JavaScript Process Timeline<br />

onclick<br />

timer code<br />

Idle<br />

0<br />

100 200<br />

300 400 500<br />

600 700 800<br />

255<br />

Timer code added to queue<br />

5<br />

Timer created with interval of 250<br />

Figure 18 - 2<br />

As you can see from Figure 18 - 2 , even though the timer code was added at the 255 - millisecond mark, it<br />

cannot be executed at that time because the onclick event handler is still running. The timer code ’ s<br />

first opportunity to be executed is at the 300 - millisecond mark, after the onclick event handler has<br />

finished.<br />

599

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!