Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearInterval() is not stopping setInterval() - Firefox Extension Development

I am working on a modification of tamper data that will allow me to send the HTTP request/responses it observes to a server. So far, that functionality has been implemented correctly. The next step is to automate this process, and I wish to use a toolbarmenu button of type 'checkbox' to toggle this functionality on and off.

So far I have this bit of code in the .XUL:

<toolbarbutton id="tamper.autosend" label="&tamper.toolbar.autosend;" type="checkbox" oncommand="oTamper.toggleTimer();"/>

And this function in the main driver of my extension:

toggleTimer : function() {
 var checked = document.getElementById('tamper.autosend').checked;

 var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);

 consoleService.logStringMessage(checked);

 if (checked) {
        var interval = window.setInterval(function(thisObj) { thisObj.sendResults(true); }, 1000, this);
 }

 else {
        window.clearInterval(interval);
 }
}

Using the consoleService I see that the value of 'checked' is indeed correct. I believe the problem lies with how I am calling clearInterval, but I'm not exactly sure how to remedy it.

Any help is greatly appreciated!

like image 677
Kotsu Avatar asked Dec 03 '22 02:12

Kotsu


2 Answers

You have defined interval inside if try to declare your variable on the start

var interval = 0;
toggleTimer : function() {
 var checked = document.getElementById('tamper.autosend').checked;

 var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);

 consoleService.logStringMessage(checked);

 if (checked) {
        interval = window.setInterval(function(thisObj) { thisObj.sendResults(true); }, 1000, this);
 }

 else {
        window.clearInterval(interval);
 }
}
like image 113
Senad Meškin Avatar answered Dec 14 '22 23:12

Senad Meškin


Your doing it wrong, each time you want to set the new interval you should clear it first

clearInterval(intervalID);

console.log('reset timer');

intervalID = setInterval(function () {
    console.log('tick');
}, refreshInterval);
like image 29
richardd Avatar answered Dec 15 '22 00:12

richardd