That code is incorrectly invoking setInterval()
and instead invoking myTimer
with a parameter of 13
just once and immediately. The code should be:
var myVar = setInterval(function(){ myTimer(13); }, 1000);
function myTimer(x) {
console.log(x);
}
Because setInterval()
requires a function reference to be passed to it, not actual code to be invoked.
What's happening is that myTimer(13)
is being invoked immediately (because that's what that line does --- invoke a function). That function then runs and prints 13
to the console and does not return anything. That "nothing" is then passed as the first argument to setInterval()
, which is supposed to be a function reference, but in your case is undefined
. undefined
can't be run every second, so nothing else happens.
Because you need to pass a parameter to myTimer
, you'll need to do that by adding parenthesis after it, but doing that invokes the function, so we wrap that function call in another function declaration and that wrapper is the function that will be called by the interval. It will in turn call myTimer(13)
.
Now, if you didn't need to pass an argument to the myTimer
function, then you wouldn't need the outer function wrapper and could just do:
var myVar = setInterval(myTimer, 1000);
function myTimer() {
console.log("13");
}
Notice that myTimer
does not have any parenthesis next to it? That's because we're not trying to invoke it, we only want to pass a reference to it.