简体   繁体   English

如何从选项页面启动和停止计时器

[英]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. 现在我在我的后台页面中有这个1分钟计时器,它永远运行我希望能够从选项页面启动和停止它。

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. Window对象的setInterval()方法以指定的毫秒数间隔重复调用要调用的函数。 setInterval() returns an opaque value that can be passed to clearInterval() to cancel any future invocations of the scheduled function. setInterval()返回一个opaque值,该值可以传递给clearInterval()以取消对调度函数的任何将来调用。 Read more about How Javascript Timers work . 详细了解Javascript定时器的工作原理 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. 现在你可以说My.Controller.startAction()启动计时器并且My.Controller.stopAction()停止。

Read and explore about namespaces in JavaScript . 阅读并探索JavaScript中的命名空间 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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