取消/停止在 jQuery/Javascript 中执行回调函数
我有一个动画设置为在超时后播放。该动画完成后会在不同的元素上重复。我正在利用 animate 方法的回调函数来启动下一个动画。我提取的代码如下所示:
function fancyAnimation() {
// Get a random object property, which is actually the id for a dot
var id = getRandomNumber( 1, 100 );
// Apply an effect to the dot
$( '#test' + id ).effect(
'pulsate',
{ times : 3 },
1000,
fancyAnimation
);
}
在单击事件上,我希望动画停止。在任何给定时间,“fancyAnimation”函数都会排队等待运行,这只是一次又一次地排队,依此类推。
有没有办法可以阻止这个函数的执行,从而结束某个事件的无限循环?如果是这样,你会怎么做?
太感谢了!
编辑:根据请求,启动 fancyAnimation
的代码。
function initiateFancyAnimation() {
animation_timeout = setTimeout( "fancyAnimation()", animation_interval );
}
I have an animation that is set to play after a timeout. This animation repeats itself over on different elements after it completes. I'm utilizing the animate
method's callback function to initiate the next animation. My extracted code looks like:
function fancyAnimation() {
// Get a random object property, which is actually the id for a dot
var id = getRandomNumber( 1, 100 );
// Apply an effect to the dot
$( '#test' + id ).effect(
'pulsate',
{ times : 3 },
1000,
fancyAnimation
);
}
On a click event, I want the animations to stop. At any given time, the "fancyAnimation" function is queued to run, which just queues it again and again and so forth.
Is there a way that I can stop this function from executing, thereby ending the infinite loop on a certain event? If so, how would you do this?
Thank you so much!
EDIT: By request, the code that initiates fancyAnimation
.
function initiateFancyAnimation() {
animation_timeout = setTimeout( "fancyAnimation()", animation_interval );
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么,简单的方法是设置一个全局标志,每次函数运行时检查该标志:
Well, the easy way would be to set a global flag that you check each time the function runs:
当用户单击该项目时,您可以将某个类应用于“点”,然后在每个循环上检查该类,如下所示:
编辑:
我过去使用的替代方案是一个名为 $.doTimeout 允许更好地控制回调。
使用此插件,您可以执行以下操作:
不确定这是否有帮助,因为回调仍在运行;但是,它允许您暂停实际动画功能的运行。
You could apply a certain class to the 'dot' when the user clicks the item and then check for that class on each loop like this:
EDIT:
An alternative that I've used in the past is a plugin called $.doTimeout which allows for the callback to be controlled a little better.
With this plugin you could do something like this:
Not sure if this helps as the callback is still run; however it would allow you to pause the actual animation function from running.
现在函数反应式编程已经到来,这里有一种使用 BaconJS 来实现这种风格的方法(虽然它并没有更短)。
工作演示位于 http://jsfiddle.net/ronaldchanou/o4hk0176/2/
Now that functional reactive programming has arrived, here's one way to do it in this style using BaconJS (though it's not any shorter).
Working demo at http://jsfiddle.net/ronaldchanou/o4hk0176/2/