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

前端 未结 4 952
醉梦人生
醉梦人生 2020-11-28 07:46

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

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 08:23

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

提交回复
热议问题