Why does the setInterval callback execute only once?

JavascriptCallbackSetinterval

Javascript Problem Overview


I have this counter I made but I want it to run forever, it's really simple, what am I doing wrong here?

function timer() {
  console.log("timer!")
}

window.setInterval(timer(), 1000)

Javascript Solutions


Solution 1 - Javascript

You used a function call instead of a function reference as the first parameter of the setInterval. Do it like this:

function timer() {
  console.log("timer!");
}

window.setInterval(timer, 1000);

Or shorter (but when the function gets bigger also less readable):

window.setInterval( function() {
  console.log("timer!");
}, 1000)

Solution 2 - Javascript

setInterval and setTimeout must be used with callbacks, like:

setInterval(timer, 1000);

or unnamed functions:

setInterval( function() { console.log("timer!"); }, 1000 );

Why your code is not working - when you pass a function as argument to another function with brackets e.g. doSomething ( someFunc() ) you are passing the result of the function.

When the function is passed as object e.g. doSomething ( someFunc ) you are passing a callback. This way someFunc is passed as reference and it is executed somewhere in the calling function. This is the same as the pointers to functions in other languages.

A common mistake is to use the these two functions as shown at w3schools. This makes an implicit call to eval.

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
Questioncomputer_smileView Question on Stackoverflow
Solution 1 - JavascriptKoen PetersView Answer on Stackoverflow
Solution 2 - JavascriptBakudanView Answer on Stackoverflow