我怎样才能等待一段时间然后更改变量?
我有一些使用 jquery 的代码,我想等待 300 毫秒,然后更改一个变量。我尝试了 setTimeout 但它不起作用,它只是使变量立即改变。
setTimeout(animationWait = 0, 300);
(我在文档中较早地定义了animationWait)基本上我想做的是等待一次单击结束,然后才能进行另一次单击。所以我想我应该设置一个变量然后等待300ms,
$('#up-arrow').live('click', function(e) {
if(animationWait == 0) {
animationWait = 1;
.... /* Code */
}
}
所以我需要在延迟运行代码后再次将animationWait更改回0。我已经尝试了很多东西,但仍然不起作用,有什么想法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您没有正确使用 setTimeout 。必须向其传递函数名称或匿名函数。
You are not using setTimeout quite right. It must be passed either a function name or an anonymous function.
您传递的参数应该是一个评估语句。对我来说这很好用:
The parameter what you pass should be an evaluation statement. For me this works fine:
您所问问题的答案是
setTimeout()
期望第一个参数是函数引用 - 在其他地方声明的函数的名称或匿名函数。 (或字符串,但出于多种原因,使用字符串几乎总是错误的解决方案。)您的代码只需执行表达式animationWait = 0
并将该表达式的结果 (0) 传递给 <代码>setTimeout()。因此,要通过
setTimeout()
执行单行代码,我建议将其包装在匿名函数中,并将该函数传递给setTimeout()
:但是,如果您是使用 jQuery 做动画,它的动画方法允许您传递一个在动画结束时执行的回调函数,因此您可以在那里进行此类处理,而不是独立设置自己的超时。例如,如果您的动画是这样的:
那么您可以添加一个回调函数,该函数将在该动画完成后调用:
在我看来,这比单独的
setTimeout()
调用更简洁,而且它更容易维护,因为只需在一处指定持续时间,而不必将自己的超时同步到动画。类似的语法适用于其他 jQuery 方法,例如
.fadeIn()
、.hide()
等。请参阅.animate()
doco 了解更多信息和示例。The answer to your question as asked is that
setTimeout()
expects the first parameter to be a function reference - either the name of a function declared elsewhere or an anonymous function. (Or a string, but for several reasons using a string is almost always the wrong solution.) Your code as is simply executes the expressionanimationWait = 0
and passes the result of that expression (0) tosetTimeout()
.So to execute your single line of code via
setTimeout()
I'd recommend wrapping it in an anonymous function and passing that function tosetTimeout()
:However, if you are doing animation with jQuery its animation methods allow you to pass a callback function to be executed when the animation ends, so you can do this type of processing there rather than independently setting your own timeout. For example, if your animation was like this:
Then you could add a callback function that will be called after this animation completes:
To my eye this is neater than a separate
setTimeout()
call, but also it is easier to maintain because the duration only has to be specified in one place rather than you having to sync your own timeout to the animation.A similar syntax applies to other jQuery methods like
.fadeIn()
,.hide()
, etc. See the.animate()
doco for more information and examples.您是否尝试过使用 jQuery 函数
delay()
?标准用例如下所示:
其中delayedEffectFunction() 是您想要延迟的虚构函数。
Have you tried using jQuery function
delay()
?A standard use case would look something like this:
Where
delayedEffectFunction()
is a made-up function you want to be delayed.