javascriptcallbacksetinterval

Why does the setInterval callback execute only once?


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)

Solution

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

    Or even shorter, using an arrow function expression:

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