你如何处理setTimeout()的多个实例? [英] How do you handle multiple instances of setTimeout()?
问题描述
阻止创建setTimeout函数的多个实例(在javascript中)的最佳推荐/最佳方法是什么?
What is the most recommended/best way to stop multiple instances of a setTimeout function from being created (in 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);
...
...
...
}
我的问题是,如果用户多次点击鼠标,我会调用moveDiv()的多个实例。
My issue is that if the user clicks the mouse multiple times, I have multiple instances of moveDiv() getting called.
我看过的选项是创建一个标志,只允许在没有其他实例可用的情况下调用超时...这是最好的方法吗?
The option I have seen is to create a flag, that only allows the timeout to be called if no other instance is available...is that the best way to go?
我希望能做到这一点清楚....
I hope that makes it clear....
推荐答案
当你调用settimeout时,它会返回一个变量handle(一个数字,我认为)
when you call settimeout, it returns you a variable "handle" (a number, I think)
如果你第二次拨打settimeout,你应该先
if you call settimeout a second time, you should first
clearTimeout( handle )
然后:
handle = setTimeout( ... )
帮助自动化,你可以使用一个将超时调用与字符串相关联的包装器(即div的id或你想要的任何东西),这样如果以前的settimeout具有相同的字符串,我t再次设置之前会自动清除它,
to help automate this, you might use a wrapper that associates timeout calls with a string (i.e. the div's id, or anything you want), so that if there's a previous settimeout with the same "string", it clears it for you automatically before setting it again,
你会使用一个数组(即字典/ hashmap)将字符串与句柄相关联。
You would use an array (i.e. dictionary/hashmap) to associate strings with handles.
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 )
}
当然还有其他这样做的方法..
There are of course other ways to do this ..
这篇关于你如何处理setTimeout()的多个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!