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

})();

6 Answers 6

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);     
6
  • 2
    But what if //do whatever here takes longer than 2 seconds? Feb 3, 2012 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. Feb 3, 2012 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. Feb 3, 2012 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. Feb 3, 2012 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 4, 2012 at 20:30
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);

})();
0
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
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);
            }
        });
    });
}());
3
  • 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. Feb 3, 2012 at 23:10
  • That would be up to the OP. 2000ms, 1700ms, whatever. At that point it's a config tweak. Feb 3, 2012 at 23:13
  • An endless recursive setTimeout will lead to a stack overflow eventually: medium.com/@devinmpierce/recursive-settimeout-8eb953b02b98
    – PRMan
    Nov 6, 2019 at 21:27
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);
  })();
})();

2
  • 1
    Be careful, since recursive setTimeout can lead to stack overflow (the error, not this site). medium.com/@devinmpierce/recursive-settimeout-8eb953b02b98
    – PRMan
    Nov 6, 2019 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, 2019 at 1: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>

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.