How do you handle multiple instances of setTimeout()?

前端 未结 9 2048
鱼传尺愫
鱼传尺愫 2020-12-01 05:18

What is the most recommended/best way to stop multiple instances of a setTimeout function from being created (in javascript)?

An example (psuedo code):



        
9条回答
  •  醉话见心
    2020-12-01 06:12

    I haven't tested any of this, and just cut this up in the editor here. Might work, might not, hopefully will be food for thought though.

    var Timeout = { 
       _timeouts: {}, 
       set: function(name, func, time){ 
         this.clear(name); 
         this._timeouts[name] = {pending: true, func: func}; 
         var tobj = this._timeouts[name];
         tobj.timeout = setTimeout(function()
         { 
    /* setTimeout normally passes an accuracy report on some browsers, this just forwards that. */
           tobj.func.call(arguments); 
           tobj.pending = false;
         }, time); 
       },
       hasRun: function(name)
       { 
           if( this._timeouts[name] ) 
           {
              return !this._timeouts[name].pending; 
           }
           return -1; /* Whut? */ 
       },
       runNow: function(name)
       {
          if( this._timeouts[name] && this.hasRun(name)===false )
          {
             this._timeouts[name].func(-1); /* fake time. *shrug* */
             this.clear(name);
          }
       } 
       clear: function(name)
       {
         if( this._timeouts[name] && this._timeouts[name].pending ) 
         {
           clearTimeout(this._timeouts[name].timeout); 
           this._timeouts[name].pending = false; 
         }
       }
    };
    
    Timeout.set("doom1", function(){ 
      if(  Timeout.hasRun("doom2") === true )
      {
         alert("OMG, it has teh run");  
      }
    }, 2000 ); 
    Timeout.set("doom2", function(){ 
       /* NooP! */
    }, 1000 ); 
    

    Successive calls with the same identifier will cancel the previous call.

提交回复
热议问题