Global Timer in Javascript with Multiple Callbacks

后端 未结 3 663
暗喜
暗喜 2021-01-19 10:39

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

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-19 11:05

    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);
    

提交回复
热议问题