Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop a recursive function

I am completely new in javascript and jquery... I have searched but can not find an answer to my problem...

I need to stop a function that call itself at the end (I read that this is called 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 function of being repeated when I click the button

What am I doing wrong?

like image 349
Tomas Lucena Avatar asked Feb 03 '17 07:02

Tomas Lucena


1 Answers

Try with: clearTimeout() in else condition .

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>
like image 90
prasanth Avatar answered Oct 24 '22 06:10

prasanth