Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 
like image 807
computer_smile Avatar asked Apr 16 '12 22:04

computer_smile


People also ask

How many times does setInterval run?

When your code calls the function repeatEverySecond it will run setInterval . setInterval will run the function sendMessage every second (1000 ms).

Does setInterval invoke the callback immediately?

Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function. This will execute the function once immediately and then the setInterval() function can be set with the required callback.

How do I repeat setInterval?

You will notice a simple trick: repeat = repeat || setInterval(reduce, 1000); This will ensure multiple intervals are not registered.

Is setInterval a callback function?

Introduction to JavaScript setInterval() The setInterval() repeatedly calls a function with a fixed delay between each call. In this syntax: The callback is a callback function to be executed every delay milliseconds.


2 Answers

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) 
like image 66
Koen Peters Avatar answered Sep 18 '22 18:09

Koen Peters


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.

like image 29
Bakudan Avatar answered Sep 19 '22 18:09

Bakudan