Reducing CPU time when using javascript

When Javascript runs with the browsers widely used today it is given all of the resources “CPU” of the browser; with today’s browsers on today’s computers that means it can get a lot done.

But! there is a problem; the browser is not responsive while the script is running. If the javascript is running for 1/30 of a second, the frame rate of video, this is not noticeable. It becomes a problem when the javascript is looping for a noticeable amount of time.

The solution is to time slice the browser resources with the javascript. In short create the loop differently … here is an example


// Set animation time in milli seconds.

var usetime = 10000;

// get start time

var d = new Date();

var start = d.getTime();

var now = d.getTime();

var done = start + usetime;

var i=0;

function loop()



var d = new Date();

var now = d.getTime();

if (now < done)


setTimeout(loop, 25); // limit to 40 fps using rest time if function uses 25 milli seconds per iteration then throughput is 20fps

} else {

document.write(i/10 + ” fps”);






Keyboard, mouse, etc, are cached so browser remains responsive.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: