Chapter 8. Taming threads and timers

 

This chapter covers

  • How JavaScript handles threading
  • An examination of timer execution
  • Processing large tasks using timers
  • Managing animations with timers
  • Better testing with timers

Timers are an often misused and poorly understood feature available to us in JavaScript, but they can provide great benefit to the developer in complex applications when used properly.

Note that we referred to timers as a feature that’s available in JavaScript, but we didn’t call them a feature of JavaScript itself—they’re not. Rather, timers are provided as part of the objects and methods that the web browser makes available. This means that if we choose to use JavaScript in a non-browser environment, it’s very likely that timers may not exist, and we’d have to implement our own version of them using implementation-specific features (such as threads in Rhino).

Timers provide the ability to asynchronously delay the execution of a piece of code by a number of milliseconds. Because JavaScript is, by nature, single-threaded (only one piece of JavaScript code can execute at a time), timers provide a way to dance around this restriction, resulting in a rather oblique way of executing code.

Note

HTML5 web workers will change a lot of this, but modern browsers aren’t quite there yet, so it’s still important to understand how browsers are currently working.

This chapter will take a look at how this all works.

8.1. How timers and threading work

8.2. Minimum timer delay and reliability

8.3. Dealing with computationally expensive processing

8.4. Central timer control

8.5. Asynchronous testing

8.6. Summary