SetInterval callback only works once

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

function timer() { console.log("timer!") } window.setInterval(timer(), 1000) 
+43
javascript callback setinterval
Apr 16 2018-12-12T00:
source share
2 answers

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

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

Or shorter (but when the function becomes larger and less readable):

 window.setInterval( function() { console.log("timer!"); }, 1000) 
+72
Apr 16 '12 at 22:40
source share

setInterval and setTimeout should be used with callbacks, for example:

 setInterval(timer, 1000); 

or unnamed functions:

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

Why does your code not work - when you pass a function as an argument to another function using brackets, for example. doSomething ( someFunc() ) you pass the result to the function.

When a function is passed as an object, for example. doSomething ( someFunc ) you pass the callback. This someFunc method is passed as a reference and executed somewhere in the calling function. This is the same as function pointers in other languages.

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

+8
Apr 17 2018-12-12T00:
source share



All Articles