Alex Rivera | Logout

How to limit the number of iterations done by setInterval

Asked 2012-07-26T19:06:11.340
17

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

Edit
Report

2 Answers

28

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

answered 2012-07-26T19:08:33.293
0

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.

var numChecks = 0;

function checkCookie()
{
    ...

    numChecks++;
    if (numChecks < 20) setTimeout("checkCookie()", 10000);
}

setTimeout("checkCookie()", 10000);
answered 2012-07-26T19:08:00.307

Your Answer