Skip to content Skip to sidebar Skip to footer

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()

Solution 1:

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

Solution 2:

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).

Solution 3:

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);

Post a Comment for "Settimeout(myfunction, 5000); Vs Settimeout(myfunction(), 5000);"