JavaScript中的全局计时器与多个回调 [英] Global Timer in Javascript with Multiple Callbacks

查看:137
本文介绍了JavaScript中的全局计时器与多个回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在javascript中创建一个全局计时器对象,然后能够即时添加回调。这样我可以在我的脚本中使用一个全局定时器以一定的间隔执行所有操作,而不是通过使用倍数浪费资源。

I want to create a global timer object in javascript and then be able to add callbacks to it on the fly. This way I can just use one global timer in my script to execute all actions at a certain interval rather than wasting resources by using multiples.

这是我想要的能够一起处理:

This is how I want to be able to piece things together:

var timer = new function() { 
 clearInterval( this.interval );

 //[1] At this point I want the Callbacks to be run

 var self = this;
 setTimeout(function() {self.timer()}, 200);
}

function otherObject = new function() {
    //When created I want to bind my object's function called cb to the global timer at [1]
}

otherObject.prototype.cb = function() {
    //Stuff that should be done every time the timer is run
}

var someObject = new otherObject();

我如何能够绑定任何数字函数(大部分是其他对象中的函数)

How would I make it possible bind any number functions (most of which are functions within other objects) to run at the interval of my timer on the fly?

推荐答案

创建一个GlobalTimer对象并赋予它注册回调函数的能力,取消自己。

Create a GlobalTimer object and give it the ability to register callback functions and cancel itself.

function makeGlobalTimer(freq) {
  freq = freq || 1000;

  // array of callback functions
  var callbacks = [];

  // register the global timer
  var id = setInterval(
    function() {
      var idx;
      for (idx in callbacks) {
        callbacks[idx]();
      }
    }, freq);

  // return a Global Timer object
  return {
    "id": function() { return id; },
    "registerCallback": function(cb) {
      callbacks.push(cb);
    },
    "cancel": function() {
      if (id !== null) {
        clearInterval(id);
        id = null;
      }
    }
  };
}

var gt = makeGlobalTimer(500);
gt.registerCallback(function() {
                      console.log("a");
                    });

gt.registerCallback(function() {
                      console.log("b");
                    });

setTimeout(function() { gt.cancel(); }, 5000);

这篇关于JavaScript中的全局计时器与多个回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆