Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

javascript - 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.

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...