Problem: javascript setTimeout executes function immediately

JavaScript has setTimeout() method which calls a function or evaluates an expression after a specified number of milliseconds. See below code,

setTimeout(function(){alert("Hello")}, 3000);

Above code will display an alert after 3 seconds. Let's take another example,

setTimeout(Func1(), 2000);

You must be thinking that "Func1()" will be executed after 2 seconds. No, You are wrong. The "Func1()" will be executed immediately, without a delay of 2 seconds. Then what setTimeout is doing over here?

Well, We need to remove the parenthesis after "Func1" . Keeping the parentheses invokes the function immediately. The reason is that the first argument to setTimeout should be a function reference, not the return value of the function. So the correct code is,

setTimeout(Func1, 2000);

But then you must be thinking how would you pass arguments to function (if function is expecting arguments)? Well, If you want to pass parameters to the function, you will have to call an anonymous function which in turn will call your function.

setTimeout(function() {
}, 2000);

You may also like:

Feel free to contact me for any help related to jQuery, I will gladly help you.

Responsive Menu
Add more content here...