You must pass a function reference to both setTimeout()
and setInterval()
. That means you pass a function name without the ()
after it or you pass an anonymous function.
When you include the ()
after the function name as in func()
, you are executing the function immediately and then passing the return result to setInterval()
or to setTimeout()
. Unless the function itself returns another function reference, this will never do what you want. This is a very common mistake for Javascript programmers (I made the same mistake myself when learning the language).
So, the correct code is:
setTimeout(func, 1500);
setInterval(func, 1500);
If you know other languages that use pointers, you can think of the name of a function with the ()
after it as like a pointer to the function and that's what a function reference is in Javascript and that's what you pass to a function when you want it to be able to execute some function later, not immediately.
When you mistakenly do this:
setTimeout(func(), 1500);
setInterval(func(), 1500);
It is executing your func()
immediately and then passing the return result to setTimeout()
and setInterval()
. Since your func()
doesn't return anything, you are essentially doing this:
func();
setTimeout(undefined, 1500);
Which is what you observe happening, but not what you want.
Further, if you want to execute a specific function call such as console.log("Bowties are cool.")
, then you can wrap it in another function like this:
setTimeout(function() {
console.log("Bowties are cool.")
}, 1500);
So, again you are passing a function reference to setTimeout()
that can be executed LATER rather than executing it immediately which is what you were doing.