Global Timer in Javascript with Multiple Callbacks

后端 未结 3 662
暗喜
暗喜 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:20

    Have the interval fire an event. The subscribing functions can listen to the event (or not) and choose to fire or not according to their own logic.

    The jQuery way of doing this would be:

    (function() {
      setInterval(function() {
        $(document).trigger('heartbeat-of-the-universe');
      }, 200);
    })();
    

    Then later inside otherObject ...

    $(document).bind('heartbeat-of-the-universe', this.cb);
    

    There are obviously other ways of implementing events.

    As the google link in the comments notes, this isn't the option with the highest performance. It is flexible and relatively forgiving however.

提交回复
热议问题