Pages

Sep 17, 2009

Passing arguments to javascript’s setTimeout() method

Javascript's setTimeout - A detailed look :
Normal set time out method which will call the method test() after 2 seconds.

setTimeout(test(), 2000 );
function test()
{
alert("Its done ! Be Happy");
}
Now the above will work fine but what happens when we want to call a method
with a delay which has arguments ? so we may go for

setTimeout(test('Enjoy'), 2000 );
function test(value)
{
alert(value);
}


Even the above method will work fine but then if we want to call a method which
may have dynamic argument then see what happens

function dynamicArgument(value)
{
setTimeout(test(value), 2000 );
}

function test(value)
{
alert(value);
}
The above is wrong and wont work so we have to follow some other way to make it work.
Lets see
function dynamicArgument(value)
{

var delay = function() { test(value); };
setTimeout(delay,2000 );
}
function test(value)
{
alert(value);
}
- here the method with argument is assigned to a var delay and used in the settimeout method.

The above will work or else we can do it still simpler like

function dynamicArgument(value){
setTimeout(test,2000,[value] );
}

function test(value)
{
alert(value);
}

Thanks
Mukunda

No comments: