简体   繁体   中英

how do I start and stop a timer from an options page

Right now i have this 1 minute timer in my background page that runs forever i would like to be able to start and stop it from an options page.

chrome.browserAction.setBadgeBackgroundColor({color:[0, 0, 0, 255]});

var i = 1;
window.setInterval(function(timer) {
chrome.browserAction.setBadgeText({text:String(i)});
i++;
}, 60000);

setInterval() method of the Window object schedules a function to be invoked repeatedly at intervals of the specified number of milliseconds. setInterval() returns an opaque value that can be passed to clearInterval() to cancel any future invocations of the scheduled function. Read more about How Javascript Timers work . With that you can write something like this:

My.Controller = {};

(function() {  
      var interval = 10;
      var timer = null;

  function init (param) {
    // initialisations if any   
  }

  // Override the default interval of 10 seconds by passing new interval 
  function startAction (param, tInterval) {
    // Set a timer
    var ti = (!tInterval) ? interval : tInterval;
    timer = setInterval(My.Controller.action, ti * 2000);    
  }

  function action () {
    // Logic here
  }

  function stopAction () { clearInterval(timer); }

  var c = My.Controller;
  c.init = init;
  c.startAction = startAction;
  c.stopAction = stopAction;
})(); // end Controller

Now you can say My.Controller.startAction() to start the timer and and My.Controller.stopAction() to stop.

Read and explore about namespaces in JavaScript . Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM