Why is the method executed immediately when I use setTimeout?
Remove the parenthesis
setTimeout(testfunction(), 2000);
If you want to send parameters to the function, you can create an anonymous function which will then call your desired function.
setTimeout(function() {
testfunction('hello');
}, 2000);
Edit
Someone suggested to send a string as the first parameter of setTimeout. I would suggest not to follow this and never send a string as a setTimeout first parameter, cause the eval function will be used. This is bad practice and should be avoided if possible.
Remove the parenthesis after the testfunction name:
setTimeout(testfunction, 2000);
The reason is that the first argument to setTimeout should be a function reference, not the return value of the function. In your code, testfunction
is called immediately and the return value is sent to setTimeout.
You're calling the function immediately and scheduling its return value.
Use:
setTimeout(testFunction, 2000);
^
Notice: no parens.