oussama kamal
oussama kamal

Reputation: 1037

Javascript clearInterval does not stop setInterval

I have a javascript code that shows some messages every 6 seconds using setInterval function as bellow:

$(function () {
    count = 0;
    wordsArray = ["<h1>Offer received</h1>", "<h1>Offer reviewed</h1>", "<h1>Decision pending</h1>", "Offer accepted.</h1>"];

    setInterval(function () {
        $(".lead").fadeOut(400, function () {
            $(this).html(wordsArray[count % wordsArray.length]).fadeIn(400);
        });
        if(count === 3){
            clearInterval(window.location.href = "www.mydomain.com");
        }
        count++;
    }, 6000);
});

When the last message is displayed I want to redirect to a URL so I checked the counter and placed a clearInterval when the last message is displayed however it does not go to the url right after the last massage is displayed but geos back to the first one and then redirect, sounds like it continues to loop. How can I fix that please?

Thanks

Upvotes: 4

Views: 2697

Answers (1)

Ajay Narain Mathur
Ajay Narain Mathur

Reputation: 5466

An interval id is returned by setInterval , you need to use that to stop particular interval.

$(function() {
  count = 0;
  wordsArray = ["<h1>Offer received</h1>", "<h1>Offer reviewed</h1>", "<h1>Decision pending</h1>", "<h1>Offer accepted.</h1>"];

  var intervalTimer = setInterval(function() {
    $(".lead").fadeOut(400, function() {
      $(this).html(wordsArray[count % wordsArray.length]).fadeIn(400);
    });
    if (count === 3) {
      clearInterval(intervalTimer);
    }
    count++;
  }, 6000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lead"></div>

Upvotes: 7

Related Questions