Question

I've tried various ways to make sure that my timer variable is global (and I believe it is) but why can't I clear the interval?

var timer;    

function refreshtimer(timer) {
  stoptimer(timer);
  timer = window.setInterval(postmsg, time*1000);
}

function stoptimer(timer) {
  window.clearInterval(timer);
  timer = null;
}

I believe this is the relevant code section; however, the entirety of the code can be found here.

Was it helpful?

Solution

You can't use the same variable name for an argument to the function and a global variable and have access to both. The argument named timer is taking precedence so you are not able to access the global variable also named timer.

Change the name of the global variable to timerId and then you can uniquely reference the one you want to reference.

var timerID;    

function refreshTimer() {
    stopTimer();
    timerID = setInterval(postmsg, time*1000);
}

function stopTimer() {
    clearInterval(timerID);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top