Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 311
That guy Avatar asked Jul 26 '12 19:07

That guy


1 Answers

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

like image 123
Alex Turpin Avatar answered Sep 27 '22 01:09

Alex Turpin