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); })();
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.
The clearInterval() method clears a timer set with the setInterval() method.
“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.
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); };
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With