How do you handle multiple instances of setTimeout()?

前端 未结 9 2049
鱼传尺愫
鱼传尺愫 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:04

    You can avoid a global or lesser variable by using a property within the function. This works well if the function is only used for this specific context.

    function set_time_out( id, code, time ) /// wrapper
    {
      if(typeof this.timeout_handles == 'undefined') this.timeout_handles = [];
    
            if( id in this.timeout_handles )
            {
                    clearTimeout( this.timeout_handles[id] )
            }
    
            this.timeout_handles[id] = setTimeout( code, time )
    }
    

提交回复
热议问题