1

I'm trying to determine how to stop a recursive function call that came from a click to 'start_button' by calling a different function when 'stop_button' is clicked.

  • User clicks 'start_button' and the slide down/up animation continues to loop "infinitely" until...
  • User clicks 'stop_button' and the looped animations will stop.

I'd like to keep two different buttons instead of having one dual-purpose start/stop button. With my code below, the animation starts and loops, but does not stop when clicking the stop button. I'd like for the stop button to stop the animation when clicked.

http://jsfiddle.net/ZdtmZ/

var stopSliding = false;

$('#stop_button').click(function(){
        stopSliding = true;
});

$('#start_button').click(function infiniteLoop(){
    if (stopSliding == true)
    {
        $('#top_message').stop();
        return;
    }       
    else
    {
        $('#top_message').hide().slideDown(2000);
        $('#top_message').slideUp(2000);    
        infiniteLoop();
        return;
    }
});
4

4 回答 4

1

您正在同步调用无限循环,这意味着任何其他 Javascript 都无法执行,例如停止按钮的单击处理程序。您需要使调用异步,以便您的点击处理程序可以执行。你可以setTimeout(infiniteLoop, 0);这样做,但你仍然不会得到你想要的行为,因为在调用无限循环之前你还没有等待滑块向上滑动。因此,您应该将infiniteLoop 作为回调传递给slideUp。这将使其异步并等待动画完成:

$('#top_message').slideUp(2000, infiniteLoop);

更新的 JSFiddle

于 2013-05-13T22:19:56.583 回答
0

我会这样写:

$('#start_button').click( function() {
    if ( stopSliding ) return false;
    $('#top_message').hide().slideDown(2000, function() {
          $('#top_message').slideUp(2000, $('#start_button').click);
    });
    return false;
});

$('#stop_button').click( function() {
    stopSliding = true;
    $('#top_message').stop();
});
于 2013-05-13T22:32:48.443 回答
0

问题可能是,当您想要停止动画时,队列中仍有大量动画等待执行(因为您的代码运行速度比实际动画快得多)。通过提供函数的可选参数clearQueuestop您可以删除所有等待动画:

$('#top_message').stop(true)
于 2013-05-13T22:22:32.093 回答
0

我只是将stopSliding变量重置为flase这种方式,如果您再次单击开始动画,它不会停止动画。

jsfiddle

var stopSliding = false;

$('#stop_button').click(function(){
    stopSliding = true;
});

$('#slide_button').click(function infiniteLoop(){
    if (stopSliding == true)
    {
        $('#top_message').stop();
        stopSliding = false;
        return;
    }       
    else
    {
        $('#top_message').hide().slideDown(2000);
        $('#top_message').slideUp(2000, infiniteLoop);
        return;
    }
});
于 2013-05-13T22:37:57.703 回答