Why does the setInterval callback execute only once?

前端 未结 2 876
独厮守ぢ
独厮守ぢ 2020-11-22 07:43

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!\")
}

win         


        
2条回答
  •  無奈伤痛
    2020-11-22 08:09

    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.

提交回复
热议问题