setTimeout and setInterval Parameters

One mistake that a lot of people seem to make is in what they specify in the first parameter when using one of these JavaScript functions. These functions expect to receive a function in the first parameter but many people mistakenly provide it with a text string. This is poor coding practice for setTimeout since where you supply:


JavaScript needs to convert that to a function in order to be able to run it and so that code is effectively treated as if you had entered it as:

setTimeout(function() {eval('myfunc()');}, 1000);

Of course what should have been specified in this instance is:

setTimeout(myfunc, 1000);

By giving the setTimeout the function it expects as the first parameter you avoid the overhead of JavaScript having to convert your text string into a function in order to be able to run it.

The situation is similar but much worse with setInterval. In this situation your code isn't just going to be run once (and hence converted from text into a function using one eval call. The conversion will be done each and every time that the code is triggered by the interval setting and so instead of one implicit eval call you effectively have an unlimited number of them evaluating the same text string.

So why not write your JavaScript properly and give these functions the function that they expect as the first parameter rather than making your code both longer and less efficient by making JavaScript convert text into a function call?


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow