停止一个递归函数

6

我完全不懂JavaScript和jQuery...我已经搜索过了,但是找不到答案解决我的问题...

我需要停止一个在结束时调用自身的函数(我听说这被称为递归函数)

所以我的HTML代码:

<div id="slide_show"></div>
<a href="#" class="stop">Stop</a>

我的js

//call effect on load
$(function() {
    moveSlide(true);
});

//move the div
function moveSlide(repeat) {
    if(repeat === true) {
        $('#slide_show').slideToggle('slow',function() {
            setTimeout(function() {
                moveSlide(true);
            },2000);
        });
    } else {
        return;
    }
}

//stop the function
$(document).on('click','.stop',function(e) {
   e.preventDefault();
   moveSlide(false);
});

这个函数被称为“永远”,但我想在点击按钮时停止该函数的重复执行。

我做错了什么?


2
repeat 设置成全局变量,怎么样?不用作为参数传递了。 - FrozenFire
2个回答

5
尝试使用clearTimeout()在else语句中。

You need to create the setTimeout() in one variable.Then apply the clearTimout() if the condition is false(Its means a else statement)

var timer;
//call effect on load
$(function() {
    moveSlide(true);
});

//move the div
function moveSlide(repeat) {
    if(repeat === true) {
      console.log('running')
        $('#slide_show').slideToggle('slow',function() {
            timer = setTimeout(function() {
                moveSlide(true);
            },2000);
        });
    } else {
      clearTimeout(timer);
       console.log('stopped')
        return;
    }
}

//stop the function
$(document).on('click','.stop',function(e) {
   e.preventDefault();
   moveSlide(false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="slide_show"></div>
<a href="#" class="stop">Stop</a>


0

我看到你在每次调用moveSlide方法时,都将其放入setTimeout中

$('#slide_show').slideToggle('slow',function() {
            setTimeout(function() {
                **///moveSlide(true); ///here , will be calling recursive untill end**
            },2000);
        });

测试并告诉我们,如果它有帮助

谢谢


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接