setTimeout(myFunction, 5000); vs setTimeout(myFunction(), 5000);

I was playing around with the "setTimeout" function. This code runs like expected:

function myFunction() {
    console.log('test');
    setTimeout(myFunction, 1000);
}
myFunction();

It prints every second 'test' to the console.

But when running this code the timeout is not waiting:

function myFunction() {
    console.log('test');
    setTimeout(myFunction(), 1000);
}
myFunction();

And it spams my console with 'test'.

The only difference in code are the brackets of myFunction() call. Why is this happening?

Answers:

Answer

That is because by including the parentheses you're actually executing the function and passing its result to setTimeout.

Answer

myFunction() calls the function immediately and passes its return value to setTimeout to be called later (except its return value is undefined, which isn't a function (or a string), so that is pointless).

Answer

setTimeout(myFunction(), 1000); means that your pass result returned by myFunction() as the 1st argument of setTimeout. myFunction returns nothing, so setTimeout(myFunction(), 1000); is the same as setTimeout(undefined, 1000);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.