Friday, 9 January 2015

javascript setTimeout function


 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(FuncDemo(), 3000);

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

Well, We need to remove the parenthesis after  "FuncDemo" . 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(FuncDemo, 3000);

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 () {
        FuncDemo('hello');
    }, 3000);


No comments:

Post a Comment