6

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?

Tomas Lucena
  • 1,204
  • 1
  • 14
  • 31

2 Answers2

4

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>
prasanth
  • 22,145
  • 4
  • 29
  • 53
0

I see that you are calling ever time at the method moveSlide, into the setTimeout

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

Test and tell us, if will help it

tks

Álvaro Touzón
  • 1,247
  • 1
  • 8
  • 21