0

I have the following code:

var timer = 15;

$("body").on("keyup", function(event) {
  var tickerInterval = setInterval(clock_ticker, 1000);
});

function clock_ticker() {
  timer--;
  // Does a bunch of things

  console.log(timer);

  if(timer == 0) {
     clearInterval(tickerInterval);
  }
}

However, it gives me an error about tickerInterval not being defined. What am I doing wrong here?

Real Noob
  • 1,369
  • 2
  • 15
  • 29
  • @David I will update the question with more information. :) – Real Noob Jun 03 '22 at 19:19
  • 1
    because `var tickerInterval` is defined in the function and it is not accessible outside of that function! It is a basic scope problem. – epascarello Jun 03 '22 at 19:22
  • @epascarello Isn't the variable inside a parent function? I thought that would make it accessible inside `clock_ticker` as well. Is that wrong? – Real Noob Jun 03 '22 at 19:24
  • No, there is no parent function. – epascarello Jun 03 '22 at 19:24
  • @epascarello Isn't the callback I defined for `keyup` event considered a parent function? – Real Noob Jun 03 '22 at 19:25
  • just because a function calls another function, it does not get any of the local variables from that block scope. – epascarello Jun 03 '22 at 19:25
  • `var tickerInterval; $("body").on("keyup", function(event) { if (!tickerInterval) { tickerInterval = setInterval(clock_ticker, 1000); } });` – epascarello Jun 03 '22 at 19:26
  • Thanks @epascarello :). I didn't use this part `if (!tickerInterval)` because it works without that as well. Just to be clear, I was defining the variable inside the `keyup` callback. and the `clock_ticker` function is also called within the same callback. So, why didn't it have access to the variable `tickerInterval`? – Real Noob Jun 03 '22 at 19:32
  • Isn't that the same thing as creating a variable in the global scope and then using it within a function we defined? If it is different, then how is it different? – Real Noob Jun 03 '22 at 19:32

0 Answers0