How do you handle multiple instances of setTimeout()?

前端 未结 9 2039
鱼传尺愫
鱼传尺愫 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:19
    var timeout1 = window.setTimeout('doSomething();', 1000);
    var timeout2 = window.setTimeout('doSomething();', 1000);
    var timeout3 = window.setTimeout('doSomething();', 1000);
    
    // to cancel:
    window.clearTimeout(timeout1);
    window.clearTimeout(timeout2);
    window.clearTimeout(timeout3);
    
    0 讨论(0)
  • 2020-12-01 06:20

    You could store multiple flags in a lookup-table (hash) using objID as a key.

    var moving = {};
    
    function mouseClick()
    {
      var objID = "div_0001";
      if (!moving[objID])
      {
        moving[objID] = true;
        moveDiv("div_0001", mouseX, mouseY);
      }
    }
    
    0 讨论(0)
  • 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"]); 
    
    0 讨论(0)
提交回复
热议问题