你如何处理setTimeout()的多个实例?

Mar*_*kus 21 javascript

阻止创建setTimeout函数的多个实例的最佳推荐/最佳方法是什么(在javascript中)?

一个例子(伪代码):

function mouseClick()
{
   moveDiv("div_0001", mouseX, mouseY);
}

function moveDiv(objID, destX, destY)
{
   //some code that moves the div closer to destination
   ...
   ...
   ...

   setTimeout("moveDiv(objID, destX, destY)", 1000);
   ...
   ...
   ...
}
Run Code Online (Sandbox Code Playgroud)

我的问题是如果用户多次点击鼠标,我会调用多个moveDiv()实例.

我看到的选项是创建一个标志,只允许在没有其他实例可用的情况下调用超时...这是最好的方法吗?

我希望说清楚......

has*_*sen 27

当你调用settimeout时,它会返回一个变量"handle"(一个数字,我认为)

如果你第二次调用settimeout,你应该先

clearTimeout( handle )
Run Code Online (Sandbox Code Playgroud)

然后:

handle = setTimeout( ... )
Run Code Online (Sandbox Code Playgroud)

为了帮助自动执行此操作,您可以使用将超时调用与字符串相关联的包装器(即div的id或您想要的任何内容),这样如果之前的settimeout具有相同的"字符串",它会自动为您清除它重新设置,

您将使用数组(即字典/散列映射)将字符串与句柄相关联.

var timeout_handles = []    
function set_time_out( id, code, time ) /// wrapper
{
    if( id in timeout_handles )
    {
        clearTimeout( timeout_handles[id] )
    }

    timeout_handles[id] = setTimeout( code, time )
}
Run Code Online (Sandbox Code Playgroud)

当然还有其他方法可以做到这一点..


spl*_*tne 5

我会这样做:

// 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"]); 
Run Code Online (Sandbox Code Playgroud)