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

Solution 1:

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:

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:

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