How to limit the number of iterations done by setInterval

前端 未结 5 2274
别那么骄傲
别那么骄傲 2021-01-04 05:34

I display video ads to my users. I don\'t host these ads by the way; I get them from another company.

When ever an ad is clicked it leaves a cookie in the user\'s b

5条回答
  •  佛祖请我去吃肉
    2021-01-04 06:23

    When you call setInterval, it returns you an interval ID that you can then use to stop it by calling clearInterval. As such, you'll want to count the iterations in a variable, and once they've reached a certain count, use clearInterval with the ID provided by setInterval.

    var iterations = 0;
    var interval = setInterval(foo, 10000);
    function foo() {
        iterations++;
        if (iterations >= 5)
            clearInterval(interval);
    }
    

    Live example

提交回复
热议问题