Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...