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 />

Firefox ’ s implementation of timers actually allows you to determine how far behind a timer has slipped.<br />

It does so by passing in the differential between the time that it was executed and the interval specified.<br />

Here is an example:<br />

//works in Firefox only<br />

setTimeout(function(diff){<br />

if (diff > 0) {<br />

//call is late<br />

} else if (diff < 0){<br />

//call is early<br />

} else {<br />

//call is on time<br />

}<br />

}, 250);<br />

When the execution of one set of code is complete, the JavaScript process yields for a short amount of<br />

time so that other processes on the page can be executed. Since the JavaScript process blocks other page<br />

processes, these small breaks are necessary to prevent the user interface from locking (which can still<br />

happen during long - running code). Setting a timer ensures that there will be at least one process break<br />

before the timer code is executed.<br />

Most browsers don ’ t distinguish intervals that are less than 10 milliseconds. Any<br />

timers set between 1 and 10 milliseconds tend to be treated the same way. Chrome<br />

has a very precise timer mechanism that is accurate to within 2 milliseconds.<br />

Repeating Timers<br />

Timers created using setInterval() ensure regular injection of timer code into the queue. The problem<br />

with this approach is that the timer code may not finish execution before the code is added to the queue<br />

again. The result would be that the timer code is run multiple times in a row, with no amount of time<br />

between them. Fortunately, JavaScript engines are smart enough to avoid this issue. When using<br />

setInterval() , timer code is added to the queue only if there are no other instances of the timer code<br />

already in the queue. This ensures that the time between additions of the timer code to the queue is, at a<br />

minimum, the specified interval.<br />

The downside to this regulation of repeating timers is twofold: (1) intervals may be skipped, and (2)<br />

intervals may be smaller than expected between multiple timer-code executions. Suppose you have a<br />

situation where an onclick event handler sets a repeating timer using setInterval() at any interval<br />

of 200 milliseconds. If the event handler takes a little over 300 milliseconds to complete, and the timer<br />

code takes about the same amount of time, you ’ ll end up with both a skipped interval and timer code<br />

running back - to - back. See Figure 18 - 3 .<br />

600

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

Saved successfully!

Ooh no, something went wrong!