Stop recursive function

I am completely new in javascript and jquery ... I searched, but cannot find the answer to my problem ...

I need to stop a function that calls itself at the end (I read that this is called a recursive function)

So my html

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

My 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);
});

The function is called forever, but I want to stop the repeat function when I press the button

What am I doing wrong?

+4
source share
2 answers

Try: otherwise. clearTimeout()

You need to create setTimeout()in one variable. Then apply clearTimout()if the condition is false (this means the 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>
Run codeHide result
+3
source

, moveSlide, setTimeout

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

,

0

Source: https://habr.com/ru/post/1668707/


All Articles