Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 204
oussama kamal Avatar asked Mar 11 '23 13:03

oussama kamal


1 Answers

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>
like image 105
Ajay Narain Mathur Avatar answered Mar 31 '23 23:03

Ajay Narain Mathur