68

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

})();
Ivar
  • 6,138
  • 12
  • 49
  • 61
Alisso
  • 1,861
  • 1
  • 17
  • 32

6 Answers6

167

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);     
Mark Rhodes
  • 10,049
  • 4
  • 48
  • 51
  • 2
    But what if `//do whatever here` takes longer than 2 seconds? – AlienWebguy Feb 03 '12 at 22:32
  • 3
    It doesn't matter, it's synchronous - it will do the stuff in the function then it will wait for 2s. So the whole thing will take more than the number of times run times 2s. – Mark Rhodes Feb 03 '12 at 22:51
  • 1
    She's doing an animation. Your function won't wait for the animation to complete unless you put your function in the animation's callback. – AlienWebguy Feb 03 '12 at 23:01
  • 3
    Sorry I get it now - if the bit in the loop start an asynchronous animation that could take > 2 seconds, got you - yes in that case it's better to use a timeout like you suggest, but I guess that's not specifically what the question is asking about. – Mark Rhodes Feb 03 '12 at 23:02
  • 1
    I got the second one working! So now I can tweak and make is so that the animation stops after some time :) – Alisso Feb 04 '12 at 20:30
  • How to execute other thing in Ionic when interval finishes? cannot use "then" or whatever – M. Mariscal Oct 12 '20 at 08:57
9

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

})();
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
7

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
Iftikhar Hussain
  • 313
  • 3
  • 14
2

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);
  })();
})();
vsync
  • 118,978
  • 58
  • 307
  • 400
  • 1
    Be careful, since recursive setTimeout can lead to stack overflow (the error, not this site). https://medium.com/@devinmpierce/recursive-settimeout-8eb953b02b98 – PRMan Nov 06 '19 at 21:26
  • @PRMan the linked article uses hand waving explanation and appears to be false: each callback made for expired timeouts comes from the event loop with a fresh call stack. Calling `setTimeout` from within such a callback will not cause stack overflow. – traktor Nov 24 '19 at 01:39
2

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

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>
 
 <div
        :class="removeAlert ? 'remove-alert' : ''"
        role="alert"
      >
        Data loaded successfully
      </div>
Walid Bousseta
  • 1,329
  • 2
  • 18
  • 33
2

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);
            }
        });
    });
}());
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • Good point, although it would look different like this, I guess you'd need to alter the 2000 value, by taking the time it took to complete the animation away. – Mark Rhodes Feb 03 '12 at 23:10
  • That would be up to the OP. 2000ms, 1700ms, whatever. At that point it's a config tweak. – AlienWebguy Feb 03 '12 at 23:13
  • An endless recursive setTimeout will lead to a stack overflow eventually: https://medium.com/@devinmpierce/recursive-settimeout-8eb953b02b98 – PRMan Nov 06 '19 at 21:27