IMG-LOGO

How to pass parameters in setTimeout function in Javascript?

andy - 24 Dec, 2013 4313 Views 0 Comment

You probably wonder how you can pass parameter variables in the setTimeout function. As we know that the setTimeout only accept two parameters, one is the method/function name and the second is the timeout length (in milliseconds). See the following script illustration.

function setTimeout("javascript function name", milliseconds);

Instead of placing the function/method name, you can actually insert a function method closure to wrap it. See below example:

//This will load a sample function after 2 seconds using setTimeout method
setTimeout(function() { sampleFunction(1, 2) }, 2000);

function sampleFunction(parameter1, parameter2) {
      alert("The first parameter1 is " + parameter1 + " and second parameter2 is " + parameter2);
}

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles