Skip a setInterval

2

$(function(){ 
   var i = 0;
   var myVar = setInterval(function(){
   $('#numero').html(i);
          i++;
   }, 5000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="numero"></div>
<button id="boton">pulsame</button>

What could I do so that by pressing the "pulsame" button the div with id "number" would pass to the next number without needing to wait for 5 seconds and then continue every 5 seconds?

    
asked by Ricardo Alvarado 06.04.2018 в 02:52
source

1 answer

1

You have to clear the interval and launch a new one. To follow the clue define a variable that contains it and so you can clean it and redefine it.

Here is a draft of how you can implement it.

var i = 0;
function cuenta(){
   $('#numero').html(i);
   i++;
}

var myTimer;

function empezarCuenta(n){
  i = n;
  clearInterval(myTimer);
  myTimer = setInterval(cuenta, 5000);
}

$(function(){ 
   $('#boton').click(function(){cuenta();empezarCuenta(i);});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="numero"></div>
<button id="boton">pulsame</button>

i, myTimer and account are left out to be more global

A more elegant solution can be found here: link

    
answered by 06.04.2018 / 04:03
source