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

前端 未结 4 953
醉梦人生
醉梦人生 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:27

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

提交回复
热议问题