Why is the method executed immediately when I use setTimeout?

JavascriptSettimeout

Javascript Problem Overview


I'm trying to write a simple code with a setTimeout, but the setTimeout just won't wait the time it's supposes to and the code execute immediately. What am I doing wrong?

setTimeout(testfunction(), 2000);

Javascript Solutions


Solution 1 - Javascript

You're calling the function immediately and scheduling its return value.

Use:

setTimeout(testFunction, 2000);
                       ^

Notice: no parens.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

Well you might have got the answer but I am explaining the cause and solution. There are two ways in which you can call a function after required amount of time.

  1. setTimeout("FUNC_NAME ()', TIME_IN_MS);
    Here FUNC_NAME inside double quotes is the original function you want to call after TIME_IN_MS milliseconds. This is because if you do not put the quotes then while java script is getting interpreted the function would be immediately executed and your purpose would get defeated. To let interpreter skip the statement we need to put quotes here.
  2. setTimeout(function () {FUNC_NAME ()}, TIME_IN_MS);
    Here anonymous function is created that tells interpreter to execute if after certain time instead of evaluating time.

Thanks shaILU

Solution 5 - Javascript

First remove the parenthesis:

setTimeout(testfunction, 2000);

And then, if you want to pass parameters in setTimeout function, you can pass in this way:

 setTimeout(testfunction, 2000, param1, param2);

Note: You can pass multiple parameters according to your function requirement.

Solution 6 - Javascript

Remove the parenthesis, currently you are invoking the function immediately. What is currently being passed to setTimeout is the returned value from the testfunction() call, but what you should pass to setTimeout as the first argument is a function reference

setTimeout(testfunction, 2000);

Solution 7 - Javascript

Anyone experiencing issues not related to calling the function immediately and using Node.js, your timeout value may be too large causing the delay to default 1.

e.g. setTimeout(testFunction, 21474836471) == setTimeout(testFunction, 1)

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

Solution 8 - Javascript

I see a lot of answers here, but I just want to take some time to explain the root cause of the problem.

Actually setTimeOut() function is an asynchronous function and when you pass a function as one of the parameter to the setTimeOut() function, your script actually does not want to waste your time and wants to execute your passed function as soon as possible.

So there are few ways in which you can bypass this. You can either use callbacks or promises.

Refer to this link for quick detail: https://www.w3schools.com/js/js_promise.asp

I will show you how can you use callback to achieve what you want to achieve.

By doing -

setTimeOut(your_function_name_without_parentheses, <number of milliseconds>)

You can actually tell your timeout that please execute yourself first and then execute my callback function passed as the first parameter.

Or if you want to pass a parameter to the callback function, you can do something like this -

setTimeOut(() => {your_function_name_with_parentheses(argument_that_you_want_to_pass), <number of milliseconds>})

There are other ways as well which are already answered above.

Also, I am a newbie to JS, please let me know if there are any gaps in my understanding.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdlerView Question on Stackoverflow
Solution 1 - JavascriptMatView Answer on Stackoverflow
Solution 2 - JavascriptJose FaetiView Answer on Stackoverflow
Solution 3 - JavascriptEmil VikströmView Answer on Stackoverflow
Solution 4 - JavascriptshaILUView Answer on Stackoverflow
Solution 5 - JavascriptShraddhaView Answer on Stackoverflow
Solution 6 - JavascriptJonathan Utsu UndelikwoView Answer on Stackoverflow
Solution 7 - JavascriptmdeforestbrownView Answer on Stackoverflow
Solution 8 - JavascriptShubham AryaView Answer on Stackoverflow