Tuesday, March 5, 2013

Passing parameters to setInterval & setTimeout

Sometimes we need to play with timed events. JavaScript comes to the rescue giving access to setTimeout and setInterval. The first one fires only once after a certain amount of time passes, while the second one fires every time a given interval passes. For example if we give 1000 as one of the input variables to setInterval, it will fire every second.

One problem that may arise using these functions is when we want to call a function defined somewhere else and pass a parameter to it. If we try to do the following:

var myFun = function(param) {
    //do something
}

var myParam = 'parameter';

setTimeout(myFun(myParam), 1000);


Instead of executing the function after 1000ms, it will execute it immediately. This is because the compiler first interprets the function calls, like myFun(myParam), and then passes the result as the callback to the setTimeout function. To avoid this, the usual way is to pass function as a variable, thus omitting the parentheses. This of course leads to one problem: how to pass parameters to the callback function? It is done in the following way:

var myFun = function(param) {
    //do something
}

var myParam = 'parameter';

setTimeout(myFun, 1000, myParam, ...);


The three dots there indicates that each following input parameter will be treated as an input parameter to the callback function. The same concept applies for the setTimeout function.
Categories:

1 comment:

  1. For men also have the right to stand out and to be stylish. Today lots of rolex replica uk are targeted at men, no matter which style or on what occasion they'll use it from such as for show, for sport, formal etc. they would always find suitable hublot replica uk to match the different occasion they want to attend. If you are tag heuer replica is not an issue when you want to buy a timepiece then you could always buy one of the designer rolex replica sale but if you only have limited budget in your hand a replica will do the trick. However you have to make sure that when you buy a replica you have to buy it on a reliable dealer that sells quality rolex replica uk. Luxury are not for the wealthy alone, for everyone has the right to have luxurious things they want. Although the original thing may be very expensive and not everyone can afford them ordinary people still have the right to have luxurious thing it's just that they should considered their budget and settle for replica watches uk with a good quality rather than force themselves to buy the original one and end up bankrupt.

    ReplyDelete