Max
Max

Reputation: 116

Jquery function display different alerts at the same time setInterval

I have this function, which shows alerts of an especific value each 2 seconds.

jQuery.fn.ShowAlert = function(value){
   var value=value;
       setInterval( function(){alert(value);},2000)

 }

 $("#show1").on("click", function(){  $(document).ShowAlert(4);});
 $("#show2").on("click", function(){  $(document).ShowAlert(3);});
 $("#show3").on("click", function(){  $(document).ShowAlert(2);}); 

       $(document).ShowAlert(4); /*by default the page start alerting the number 4*/

So anytime I click an anchor, the page starts popping up alerts of the value selected each 2 seconds.

 <a id=show1>Show value 4</a>
 <a id=show2>Show value 3</a>
 <a id=show3>Show value 2</a>

the problem is, once I click more than one anchor, the function start popping up different alerts displaying the value 4 & 3 or 4 & 2 or 4,3 & 2, etc.

The question is how do I stop this behaviour? What I want is to click an anchor and the function displays alerts of the number selected only. https://jsfiddle.net/vyucptve/

Upvotes: 0

Views: 172

Answers (3)

Suraj
Suraj

Reputation: 373

Try this:

$(document).ready(function() {
jQuery.fn.ShowAlert = function(value){
   var value=value;

   var timerId = setInterval( function()
    {
        alert(value);
        value = value-1;
        if(value<1) {
            clearInterval(timerId);
        }

    },2000)



 }

   $(document).ShowAlert(4);     
});
</script>

<a id="show1">Show value 4</a>
<a id="show2">Show value 3</a>
<a id="show3">Show value 2</a>

Upvotes: 1

tanmay
tanmay

Reputation: 7911

You need to clear interval using clearInterval (MDN) function to start fresh when you click on a different link. Something like this can do the trick.

var myInterval;
jQuery.fn.ShowAlert = function(value){
   var value = value;
   if(myInterval) {
       clearInterval(myInterval);
       myInterval = null;
   }
   myInterval = setInterval( function(){alert(value);},2000)
}

Upvotes: 1

Lewis Vail
Lewis Vail

Reputation: 1

The setInterval function returns a number that is a reference to that interval. You can stop an interval by calling clearInterval and passing in the reference to the previous interval.

Upvotes: 0

Related Questions