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

编程入门 行业动态 更新时间:2024-10-26 11:26:14
本文介绍了你如何处理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()的多个实例?

本文发布于:2023-11-25 14:20:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630100.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   如何处理   实例   setTimeout

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!