如何限制setInterval执行的迭代次数 [英] How to limit the number of iterations done by setInterval
问题描述
我向用户展示视频广告。我不会托管这些广告的方式;我从另一家公司得到他们。
I display video ads to my users. I don't host these ads by the way; I get them from another company.
点击广告时,会在用户的浏览器中留下一个Cookie。
我创建了一个函数,每10秒检查一个cookie的存在。
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.
我想做的是限制的次数函数可以运行或可以运行的秒数。
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.
以下是函数:
function checkCookie()
{
var cookie=getCookie("PBCBD2A0PBP3D31B");
if (cookie!=null && cookie!="")
{
alert("You clicked on an ad" );
}
setInterval("checkCookie()", 10000);
我想限制 setInterval(checkCookie(),10000);
可以使
推荐答案
当您调用 setInterval
,它会返回一个间隔ID,您可以使用该ID来停止它,方法是调用 clearInterval
。因此,您需要计算变量中的迭代次数,一旦达到某个计数,请使用 clearInterval
(由 <$ c)提供的ID $ c> setInterval 。
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
这篇关于如何限制setInterval执行的迭代次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!