How do you handle multiple instances of setTimeout()?

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

    I would do it this way:

    // declare an array for all the timeOuts
    var timeOuts = new Array();  
    
    // then instead of a normal timeOut call do this
    timeOuts["uniqueId"] = setTimeout('whateverYouDo("fooValue")', 1000);  
    
    // to clear them all, just call this
    function clearTimeouts() {  
      for (key in timeOuts) {  
        clearTimeout(timeOuts[key]);  
      }  
    }  
    
    // clear just one of the timeOuts this way
    clearTimeout(timeOuts["uniqueId"]); 
    

提交回复
热议问题