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

JavascriptLoops

Javascript Problem Overview


I've created a loop of "changing words" with jQuery by using the code in this answer: https://stackoverflow.com/questions/7425231/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);

})();

Javascript Solutions


Solution 1 - Javascript

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);     

Solution 2 - Javascript

Use clearInterval to clear the interval. You need to pass the interval id which you get from setInterval method.

E.g.

var intervalId = setInterval(function(){
                    ....
                 }, 1000);

To clear the above interval use

clearInterval(intervalId);

You can change your code as below.

(function(){

    // List your words here:
    var words = [
        'Lärare',
        'Rektor',
        'Studievägledare',
        'Lärare',
        'Skolsyster',
        'Lärare',
        'Skolpsykolog',
        'Administratör'
        ], i = 0;

    var intervalId = setInterval(function(){
        $('#dennaText').fadeOut(function(){
            $(this).html(words[i=(i+1)%words.length]).fadeIn();
            if(i == words.length){//All the words are displayed clear interval
                 clearInterval(intervalId);
            }
        });
       // 2 seconds
    }, 2000);

})();

Solution 3 - Javascript

The simplest solution is

var intervalId =   setInterval(function() {
    $('#dennaText').fadeOut(function() {
        $(this).html(words[i = (i + 1) % words.length]).fadeIn();
    });
}, 2000); // run every 2 seconds

setTimeout(function(){
    clearInterval(intervalId);
},10000) // stop it after 10seconds

Solution 4 - Javascript

You should consider using a recursive setTimeout() instead of setInterval() to avoid a race condition.

var fadecount = 1;
(function interval(){  
    $('#dennaText').fadeOut(function(){
        $(this).html(words[i=(i+1)%words.length]).fadeIn('fast',function(){
            if (fadecount < 30){
                fadecount += 1;
                setTimeout(interval, 2000);
            }
        });
    });
}());

Solution 5 - Javascript

You can use setTimeout instead, which is better:

(function foo(){ // wrap everything in a self-invoking function, not to expose "times"
  times = 20; // how many times to run
  (function run(){
    // do your stuff, like print the iteration
    document.body.innerHTML = times;

    if( --times ) // 200 * 20 = 4 seconds
      setTimeout(run, 100);
  })();
})();

Solution 6 - Javascript

I'm working with VueJs and wanted to remove a div after few seconds; here's what I did, I hope that could help someone ;).

 <div
        :class="removeAlert ? 'remove-alert' : ''"
        role="alert"
      >
        Data loaded successfully
      </div>

export default {
  name: "Home",
  components: {},
  data() {
    return {
      removeAlert: false,
    };
  },
  methods: {
    removeAlertF() {
      let wait = window.setInterval(() => {
        this.removeAlert = true;
        console.log("done");
        if(true){
          window.clearInterval(wait);
        }
      }, 3000);
    },
  },
  mounted() {
    this.loadData();
    this.removeAlertF();
  },
};

<style>
.remove-alert {
  display: none;
}
</style>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlissoView Question on Stackoverflow
Solution 1 - JavascriptMark RhodesView Answer on Stackoverflow
Solution 2 - JavascriptShankarSangoliView Answer on Stackoverflow
Solution 3 - JavascriptIftikhar HussainView Answer on Stackoverflow
Solution 4 - JavascriptAlienWebguyView Answer on Stackoverflow
Solution 5 - JavascriptvsyncView Answer on Stackoverflow
Solution 6 - JavascriptWalid BoussetaView Answer on Stackoverflow