Friday, June 15, 2007

Javascript setInterval() and setTimeout() argument passing

Update: I've modified the post in order to rant about IE not supporting anything after the 2nd argument. Also, I've fixed the example to remind myself of the cross-browser supported syntax.

Just a quick posting to remind myself...

setInterval( function() { fxn(arg[,args]...)} , TimeBetweenIntervals)
setTimeout( function() { fxn(arg[,args]...)} , DelayTimeBeforeTrigger)

If you have a function that doesn't need to reference elements in the DOM (IE it's not a generic function that isn't hardcoded to reference DOM elements or variables) then you can pass in text as a string.

Ex.) myInterval = window.setInterval("displayTime()",1000);

If however, you need to pass variables into an interval or timout that could vary, then use the following:

Ex.) myTimeout = window.setTimeout( function() {displayTime(document.getElementById('clockDiv'))},1000);

Your displayTime() function would accept a DOM element that it would target in order to swap out the time value. This DOM element can then vary between distinct instances of intervals. For instance, you could have a page that is timing different processes and displays the run time for each process in a different div - all of which are using the same displayTime() method to change the HTML.

2 comments:

  1. Passing strings to setTimeout() is a form of eval(), and therefore very slow and bad form (see http://blogs.msdn.com/ericlippert/archive/2003/11/01/53329.aspx).

    Doing this can get quite cumbersome, especially with objects, so I wrote a utility function: http://fn-js.info/snippets/bind.

    ReplyDelete
  2. Twey is correct, passing in a string is an implied eval(). You can, however, pass in a function as the first parameter using this syntax: setInterval(displayTime, 1000); Be aware, however, that the parameters that get passed to the function using this syntax tend to be somewhat unpredictable. Using this syntax with a 1 second timeout and tracing the input arguments, I seem to randomly receive 0, 1, or -15 as the input parameter to my function.

    If your function doesn't care about input parameters in any way that's probably acceptable. Otherwise, the syntax above using an anonymous function is probably the best approach.

    ReplyDelete