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>

Answer from prasanth on Stack Overflow
🌐
Reddit
reddit.com › r/learnjavascript › stopping a recursive function?
r/learnjavascript on Reddit: Stopping a recursive function?
February 8, 2021 -

I wanted to get some practice working with Date.now and the date object within JS so I started working on a stop watch.

The problem I am having is with a recursive function I used to update the time. It seems the issue is related to the recursive function continuing to run updateTime() indefinitely, even when the state of the clock has been set to paused.

Codpen: https://codepen.io/bluehabit/pen/PKVQMq

if(startTime){
		setTimeout(function(){

			difference = timeDifference(baseTime, endTime);
			convertedDifference = convertTime(difference);

			var seconds = convertedDifference.seconds;
			var minutes = convertedDifference.minutes;
			var milliseconds = convertedDifference.milliseconds;

			console.log(convertedDifference);
			printTimeResult(convertedDifference)
			updateTime();
		}, 3);
	} else {
		return;
}

When I pause the timer the recursive function continues to run in the background updating the time.

For example if you were to start the timer, pause it at 5 seconds and were to wait an additional 5 seconds. The function continues to run in the background and the time would be 10 seconds instead of 5 where you left off when you resume the timer.

Here is an example of this issue:

http://imgur.com/66HJfdt

Discussions

jquery - How to Stop a Recursive Function in JavaScript? - Stack Overflow
I'm stuck looking for the right way to stop a setTimeout call recursive function. I want to be able to restart an animation without having to wait for the animation to finish. Any help would be a... More on stackoverflow.com
🌐 stackoverflow.com
February 25, 2016
Break out of Javascript recursive function on .click()
I want the slider to autoplay on ... using a recursive (I think?!!) function called autoPlay() (see line 50). However, I want the user to be able to interact with the slider using previous/next and pagination buttons. I have set these up and they work (see below autoPlay function). The problem is that autoplay and the navigation don't work together. I can't get the autoPlay function to stop / break when ... More on teamtreehouse.com
🌐 teamtreehouse.com
2
November 5, 2014
jquery - How to externally pause and stop recursive javascript function - Stack Overflow
I have a function which calls itself with a pause of 2 seconds until the ajax call returns 0. Now it can go on for a long time, hence i wish to pause it or stop it with an external event like a but... More on stackoverflow.com
🌐 stackoverflow.com
April 29, 2017
javascript - How to stop function recursion - Stack Overflow
I have a recursive function that call itself. But I want to stop it at a certain situation, something like break, of course it's not a loop so i can't use break. Is there any method? Thank you Fun... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-program-to-forced-exit-from-recursion
JavaScript Program to Forced Exit from Recursion | GeeksforGeeks
September 22, 2023 - Recursion is a powerful programming technique that involves calling a function to solve a problem in smaller parts. However, during recursive operations, there may be scenarios where we need to forcibly exit the recursion to prevent an infinite loop or avoid unnecessary computations. In this article, we'll explore common situations where forced exit from recursion is necessary and how to implement solutions to handle them in JavaScript, specifically in the context of React components.
Find elsewhere
🌐
Reddit
reddit.com › r/learnjavascript › how to stop recursive function with awaits inside of it
r/learnjavascript on Reddit: How to stop recursive function with awaits inside of it
August 8, 2023 -

I want to stop this function but I'm not sure how, I'm using React. I can't use a while(boolean) because I'd have to wait until all the code inside the function is done in order for the function to stop. My solution was to add an if statement for every step of the function and a setInterval inside the resolveAfter, but it's a really messy solution but I think it could work. Is there any better way to deal with this problem?

const resolveAfter = (delay: number) =>
  new Promise<void>((resolve) => {
    setTimeout(() => resolve(), delay * 1000);
  });

async function startPomodoro(timers: PomodoroTimers) {
  const ringToneDuration = ringtoneRef.current?.duration
    ? ringtoneRef?.current?.duration
    : 0;
  // POMODORO
  if (!isFirstTime) {
    await playAlarm(ringToneDuration);
  }
  console.log(`Pomodoro Started, wait ${timers.pomodoro}s`);
  setIsPomodoroRunning(true);
  console.log(isPomodoroRunning);
  setFinishTime(timers.pomodoro);
  await resolveAfter(timers.pomodoro);
  // RINGTONE
  console.log(`Ringtone Started, wait ${timers.break}s`);
  await playAlarm(ringToneDuration);
  // BREAK
  console.log(`Break Started, wait ${timers.break}s`);
  setFinishTime(timers.break);
  await resolveAfter(timers.break);
  isFirstTime = false;
  startPomodoro(timers);
}
🌐
Medium
medium.com › @psutcl › breaking-down-basic-recursion-in-javascript-77663aec0771
Breaking Down Basic Recursion in JavaScript | by Polly Sutcliffe | Medium
April 12, 2020 - The base case tells the recursive part what conditions should be met in order for the recursive function to stop calling itself. If you don’t include it, the recursive part will never stop, and your computer will eventually give you an error or hang, neither of which is very fun.
🌐
Webdevtutor
webdevtutor.net › blog › javascript-break-out-of-recursive-function
How to Break Out of a Recursive Function in JavaScript
Another method to break out of a recursive function is by throwing an exception when the exit condition is met. This can be an effective way to immediately stop the recursion and handle the exceptional case outside of the recursive function. Here's how you can implement this approach: javascript ...
Top answer
1 of 4
3

Here this will stop the animate function after two seconds. I have marked the changes I made with the comment '//new change'. You can control the time in milliseconds the animation runs using the setTimeOut function. I have used 2 seconds for example. You can also set this using a random generator to get different time spans.

var animate = false; //new change

$(function () {
    $('.a').mouseenter(function() {
        animate = true;//new change
        animateDiv();
        setTimeout(function(){animate = false },2000)//new change
    });
});

function makeNewPosition() {      
   var h = $(window).height() - 50;
   var w = $(window).width() - 50;
   var nh = Math.floor(Math.random() * h);
   var nw = Math.floor(Math.random() * w);

   return [nh, nw];
}

function animateDiv() {
   var newq = makeNewPosition();
   console.log(newq);
    $('.a').animate( 
      {top: newq[0], 
       left: newq[1], }
      ,400, function () {
            if(animate) animateDiv();//new change
       });
    };

Here is a jsfiddle. Check the console log

Here is how this works. Before you begin animation in recursive function you set animation flag to true. The function calls itself only if this flag is true. Then you start a saperate timer which make animate flag false, which will cause the recursive function to break.

PS: The animation code in your original question doesn't work anyway. But i didn't try to debug it as your question was only about how to stop the function after a while.

2 of 4
0

You could do a setTimeout to stop it.

setTimeout(function (){
    $('.a').stop();
}, "1000");

This will stop any animations present on any element with the class a after 1 second.

🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript recursive function
JavaScript Recursive Function
November 15, 2024 - The function starts with an if statement that checks if n is less than or equal to 1. If n is 1 or less, the function returns n. This is the base case, which serves as the stopping condition for the recursion.
🌐
Programiz
programiz.com › javascript › recursion
JavaScript Recursion (with Examples)
The counter() function first displays count then checks if the value of count is greater than 1 with count > 1. If count > 1 evaluates to true, the program decreases the value of count and calls counter() with the new value of count (recursion). Otherwise, if count > 1 evaluates to false, the program executes the return statement, stopping the recursion.
🌐
Medium
samah-gaber.medium.com › recursion-in-javascript-52e2a3a59627
Recursion in Javascript. The function calls itself until someone… | by Samah Gaber | Medium
October 21, 2020 - To prevent running the recursion in case of wrong or bad parameters. ... In our factorial function it’s the if (x < 0) return; as it’s not possible to factorial a negative number. So we don’t even bother to run the function in this case. The Base Case is similar to our termination condition in that it also stops our recursion.
🌐
Medium
medium.com › swlh › recursive-functions-in-javascript-9ab0dd97e486
Recursive Functions in JavaScript | by Ross Mawdsley | The Startup | Medium
August 28, 2020 - So, as with the factorial example above, our recursion logic can neatly fit within a ternary statement. In this case, our escape (aka ‘exit’) condition checks if the argument passed into reverseString() will be "" and if so, an empty string "" is returned in kind, and the recursion stops.
🌐
freeCodeCamp
freecodecamp.org › news › recursion-in-javascript-simplified
How Does Recursion Work? Simplified in JavaScript with Examples
October 7, 2022 - A Base case in recursion is the halting point of the recursive function. It is the condition you specify to stop the recursion (just like stopping a loop).
🌐
CrazyEngineers
crazyengineers.com › home › threads › how to stop recursion function?
How to Stop Recursion Function? | CrazyEngineers
December 1, 2008 - Recursive functions always contain 2 parts.First that indicates action to be done by this call and second is the one that recursively calls the function again.We may specify condition that is to be satisfied for calling recursively or may also specify the condition of terminating the recursion process. For eg: In factorial we continously call until the argument passed is 1 and when argument is 1 we simply return 1 so stop the recursion