Tuesday, April 24, 2012

setInterval, the CPU and Firefox

In past and current times I've noticed the fan kicking in whenever I've visited the Kidderminster Shuttle website using Firefox; something is kicking up the CPU and thus engaging the fan, but what?

The best bet is some code constantly running and the site has two candidates for that position.

The first is a news ticker running horizontally just under the banner and the second a job posting ticker running vertically in the right-hand side bar. The news ticker runs with its own javascript writing one character at a time every 50ms before wiping out and being replaced by the next headline; that's not a problem.

The job listing uses jQuery and digging through uses the setInterval function to shift an entire ul element block upwards. Beyond shifting to three decimal places (a pixel is a pixel is a pixel) it does so using the default interval of 13ms.

To put that in perspective if you wanted to screen a movie using a function called getFrame() and thus wanted to call it every time a frame was required setInterval would need a timing of 42ms. A UK TV show would require 40ms; a US show 33ms; a video game running at 60Hz 17ms; there is very little need to ever run anything at 13ms intervals.

The odd thing is that it's only Firefox that busts the CPU. Both Chrome and IE7 handle it smoothly; Opera renders it with a jerkiness, but doesn't ratchet up the CPU. Either the former are better optimised (and who would suggest that of IE?) or it's ignoring the value and substituting something more reasonable. It's possible only Firefox is trying to do exactly what it has been told to do with the subsequent punishment being meted out on the CPU.

Okay other factors may come into play - the entire ul block is being shifted and some browsers may handle that better than others, but still if you ever need to use setInterval  for animation a timing of 30-40ms should be sufficient.

As a test I duplicated the block and created my own code to move it and found moving 1 pixel per 40ms produced a scroll effect nearly identical to the original, but without the burn.