How to limit the number of iterations done by setInterval

前端 未结 5 2260
别那么骄傲
别那么骄傲 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:10

    Passing a Callback to the Interval Function, which in turn updates a counter in the global scope:

    var countIntervals = 0,
        intervalFunc = function(_callback){
    
            console.log(countIntervals);
    
            if(countIntervals > 5) {            
                clearInterval(setIntervalVar);
            } else {
                // do stuff
                _callback();
            }
        };
    
    setIntervalVar = setInterval(intervalFunc.bind(null, function(){
        countIntervals++;
    }), 500);
    

提交回复
热议问题