Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a setInterval stop after some time or after a number of actions?

I've created a loop of "changing words" with jQuery by using the code in this answer: jQuery: Find word and change every few seconds

How do I stop it after some time? Say after either 60 seconds or after it has gone through the loop?

(function() {    // List your words here:   var words = [       'Lärare',       'Rektor',       'Studievägledare',       'Lärare',       'Skolsyster',       'Lärare',       'Skolpsykolog',       'Administratör'     ],     i = 0;    setInterval(function() {     $('#dennaText').fadeOut(function() {       $(this).html(words[i = (i + 1) % words.length]).fadeIn();     });     // 2 seconds   }, 2000);  })(); 
like image 417
Alisso Avatar asked Feb 03 '12 22:02

Alisso


People also ask

How do you make setInterval stop after some time?

To stop it after running a set number of times, just add a counter to the interval, then when it reached that number clear it.

Which function is used to stop a setInterval timer?

The clearInterval() method clears a timer set with the setInterval() method.

How do you run setInterval 5 times?

“setinterval for 5 times” Code Answer'svar intervalID = setInterval(alert, 1000); // Will alert every second. // clearInterval(intervalID); // Will clear the timer. setTimeout(alert, 1000); // Will alert once, after a second.

How do you pause a setInterval function?

To pause setInterval() functions with JavaScript, we call the clearInterval function. let doThis = null; const y = () => { //... }; doThis = setInterval(y, 1000); const yStart = () => { doThis = setInterval(y, 1000); }; const yStop = () => { clearInterval(doThis); };


1 Answers

To stop it after running a set number of times, just add a counter to the interval, then when it reached that number clear it.

e.g.

var timesRun = 0; var interval = setInterval(function(){     timesRun += 1;     if(timesRun === 60){         clearInterval(interval);     }     //do whatever here.. }, 2000);  

If you want to stop it after a set time has passed (e.g. 1 minute) you can do:

var startTime = new Date().getTime(); var interval = setInterval(function(){     if(new Date().getTime() - startTime > 60000){         clearInterval(interval);         return;     }     //do whatever here.. }, 2000);      
like image 148
Mark Rhodes Avatar answered Sep 22 '22 00:09

Mark Rhodes