0

I have this code:

var myVar = setInterval(myTimer(13), 1000);

function myTimer(x) {
  console.log(x);
}

Currently, it just prints 13 to the console once but I thought that it should print it once per second, right? Unless I'm not understanding how it works. I'm just trying to break it down on the most basic level..

pmath325
  • 61
  • 8
  • Possible duplicate of [Javascript setinterval function with arguments](https://stackoverflow.com/questions/15410384/javascript-setinterval-function-with-arguments) – Sebastian Simon Feb 24 '18 at 01:43

1 Answers1

7

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.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71