Optimization Monday — Part II: function handles
Optimization Monday August 22nd, 2007This entry is a little late, due my holiday (prearrangement), but nevertheless here is the hint for August 2007: use function handles instead of strings for window.setTimeout() and window.setInterval().
By using function handles you avoid an unnecessary evaluation of a string.
So instead of
var myHandle = window.setTimeout("doStuff()", 100);
use
var myHandle = window.setTimeout(doStuff, 100);
Of course this hint is only useful if want to call a parameter less function — which should be no problem in connection with window.setTimeout() or window.setInterval(). ;-)
Update:
Actually, there is a way for having a function call with parameters. All we need is a wrapper function and a little bit closures magic:
function wrapperFunc(firstParam, secondParam){ return (function(){ doStuff(firstParam, secondParam); }); } var myWrapper = wrapperFunc('foo', 'bar'); var myHandle = window.setTimeout(myWrapper, 100);
The real trick is that the myWrapper variable contains an anonymous function together with two variables, which were set when wrapperFunc() was called. By applying this variable to windows.setTimeout() method, the anonymous function (containing the call of doStuff()) will be executed after the given timeout.

