-4
function start (argument){
    alert("Starting Quiz!");
    var time = setInterval( timer(), 1000);

}

function timer(){
    console.log("Time: " + counter + " seconds");
}

I found that when setInterval( "timer()", 1000); works as intended repeatably calling my timer function, but when I don't use quotes "" the function is only called once. Why is that?

Ig0R44
  • 1
  • 1
  • 2
    call it without the `()` like this: `setInterval(timer, 1000)` – Get Off My Lawn Oct 24 '18 at 20:40
  • Instead of passing the function as an argument you are just executing it once. – takendarkk Oct 24 '18 at 20:41
  • The first parameter of `setInterval` wants to know *"Which function do you want to call?"*. However, instead of giving it the name of said function (`timer`), you've *executed* the function by including parentheses. Just change `timer()` to `timer`. – Tyler Roper Oct 24 '18 at 20:41

1 Answers1

0

You're executing the function yourself. You should just pass the function:

var time = setInterval(timer, 1000);

When you passed a string, you were telling it to evaluate an expression in the global context.

Frank Modica
  • 10,238
  • 3
  • 23
  • 39
  • That makes a bit more sense, but could you perhaps expand on the global context part? – Ig0R44 Oct 24 '18 at 20:58
  • @CodyIg0R44Roe: passing a string is the same as passing `new Function("...")`. Functions created this way are defined in global scope. – Felix Kling Oct 24 '18 at 21:03