-4

I have a function called "showCustomer" that get number between 1-5 and return something.

I want to use setInterval, to run this function every 5 second but with another number.

Its not working, i don't understand why its not working to me. here is the code.

setInterval(function () {
    var i = 1;
    showCustomer(i);
    i++;
}, 5000);
JJJ
  • 32,902
  • 20
  • 89
  • 102
Maxim Baran
  • 67
  • 1
  • 9

2 Answers2

2

Just move the declaration of variable i before the setInterval() call:

var i = 1;

setInterval(function () {
    showCustomer(i);
    i++;
}, 5000);

The anonymous function you've set as a callback for setInterval gets called every 5 seconds in your code. In every call, you're setting i to 1 which resets it every time.

Moving i outside the setInterval callback makes it persist the the current value.

31piy
  • 23,323
  • 6
  • 47
  • 67
  • thank you, but how i can stop when i equal to 5 and start again? – Maxim Baran Apr 14 '18 at 09:01
  • 1
    @Maxim -- please see [this post](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript). It is always a good practice to search beforehand. – 31piy Apr 14 '18 at 09:02
  • i saw this post but dont understand. – Maxim Baran Apr 14 '18 at 09:11
  • @Maxim -- but it is quite straight-forward. You assign the return value of `setInterval` in a variable, say `x`. In the callback, check if `i === 5` then call `clearinterval` with `x`. – 31piy Apr 14 '18 at 09:14
0

Every time you use var, you redeclare the value of that variable. So you only should declare the counter one time.

Every time that the browser calls the callback showCustomer the if statement evaluates if the browser should make a new call.

clearInvertal() it's the method to stop the setInterval() method.

var id = 1;

var show5times = window.setInterval(showCustomer, 5000);

function showCustomer() {

  alert(id);
  
  id++;
  
  if(id > 5) {
  
   window.clearInterval(show5times);
  
  }

}
Angel Luis
  • 322
  • 4
  • 14