javascript 如何限制 setInterval 完成的迭代次数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11676331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to limit the number of iterations done by setInterval
提问by That guy
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 browser. I've created a function that checks the existence of a cookie every 10 seconds.
当点击广告时,它会在用户的浏览器中留下一个 cookie。我创建了一个函数,每 10 秒检查一次 cookie 的存在。
What I would like to do is to limit the number of times this function can run or the number of seconds it can run for.
我想要做的是限制这个函数可以运行的次数或它可以运行的秒数。
Below is the function:
下面是函数:
function checkCookie()
{
var cookie=getCookie("PBCBD2A0PBP3D31B");
if (cookie!=null && cookie!="")
{
alert("You clicked on an ad" );
}
setInterval("checkCookie()", 10000);
So to recap. I want to limit the number of iterations that setInterval("checkCookie()", 10000);
can make
所以要回顾一下。我想限制setInterval("checkCookie()", 10000);
可以进行的迭代次数
回答by Alex Turpin
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
.
当您调用 时setInterval
,它会返回一个时间间隔 ID,然后您可以使用该 ID 通过调用来停止它clearInterval
。因此,你要在一个变量来算的迭代,而一旦他们已经达到了一定的数量,使用clearInterval
与提供的ID setInterval
。
var iterations = 0;
var interval = setInterval(foo, 10000);
function foo() {
iterations++;
if (iterations >= 5)
clearInterval(interval);
}
回答by j08691
This should do it:
这应该这样做:
function checkCookie() {
var cookie = getCookie("PBCBD2A0PBP3D31B");
if (cookie != null && cookie != "") {
alert("You clicked on an ad");
}
if (counter > 10) clearInterval(clr);
counter++;
clr = setInterval(function(){checkCookie()}, 10000);?
}
var counter = 0;
checkCookie();
回答by Mr. Polywhirl
WindowTimers.setInterval(func, delay[, param1, param2, ...])
WindowTimers.setInterval(func, delay[, param1, param2, ...])
The 3rdparameter and onward in setInterval
are optional parameters to pass to the interval function. Note, these optional arguments are not supported in IE9 and earlier.
的3次参数并向前在setInterval
是可选的参数传递给间隔功能。请注意,IE9 及更早版本不支持这些可选参数。
We can use this to our advantage by avoiding the use of global or outside-scope. as seen below. The interval function keeps track of the limit and the current increment of the counter through the opts
parameter.
我们可以通过避免使用全局或外部范围来利用这一点。如下所示。间隔函数通过opts
参数跟踪计数器的限制和当前增量。
The runTask
function takes a mandatory fn
argument which returns a boolean value to determine if the timer's task has been completed. There are two taks that are run in the example below, with each varying in the rate at which each is run and the condition to be met.
该runTask
函数采用一个强制fn
参数,该参数返回一个布尔值以确定计时器的任务是否已完成。在下面的示例中运行了两个任务,每个任务的运行速度和要满足的条件各不相同。
The first two tasks finish, but the last one runs out of attempts before the condition is met.
前两个任务完成,但最后一个任务在条件满足之前尝试次数用完。
function writeLine(el, text) {
el.innerHTML += [].slice.call(arguments, 1).join(' ') + '\n';
}
function runTask(options, interval, limit) {
var interval = setInterval(function(opts) {
opts.incr = (opts.incr || 0) + 1;
if (opts.fn(opts)) {
clearInterval(interval);
writeLine(opts.el, '>> Task finished...');
} else if (opts.incr > limit) {
clearInterval(interval);
writeLine(opts.el, '>> Exceeded limit of ' + limit);
} else {
writeLine(opts.el, '>> Attempt: ' + opts.incr + '/' + limit);
}
}, interval, options);
}
// 5 atttempts to reach 4 in 250ms.
runTask({
fn : function(opts) { return opts.incr === 4; },
el : document.querySelectorAll('div.col')[0]
}, 250, 5);
// 10 atttempts to reach 7 in 100ms.
runTask({
fn : function(opts) { return opts.incr === 7; },
el : document.querySelectorAll('div.col')[1]
}, 100, 10);
// 10 atttempts to reach 15 in 50ms.
runTask({
fn : function(opts) { return opts.incr === 15; },
el : document.querySelectorAll('div.col')[2]
}, 50, 10);
.col {
display: inline-block;
width: 175px;
font-family: monospace;
white-space: pre;
border: thin solid black;
vertical-align: top;
padding: 4px;
}
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
回答by adi518
Passing a Callback to the Interval Function, which in turn updates a counter in the global scope:
将回调传递给 Interval 函数,后者又会更新全局范围内的计数器:
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);
回答by mellamokb
You just need some sort of global counter variable to keep track. For instance, the follow code would only run the cookie check a maximum of 20 times per page load.
您只需要某种全局计数器变量来跟踪。例如,下面的代码只会在每个页面加载时最多运行 20 次 cookie 检查。
var numChecks = 0;
function checkCookie()
{
...
numChecks++;
if (numChecks < 20) setTimeout("checkCookie()", 10000);
}
setTimeout("checkCookie()", 10000);