akram
akram

Reputation: 71

how to decrease number by using var

I have a variable equal to number, so I want decrease this variable value every second. in this code it is print the same number over and over, although I have written (n--)

 var x = setInterval(function() {
    var n = 50;
    console.log(n--);
   }, 1000);

my question how I can decrease it?

Upvotes: 1

Views: 161

Answers (4)

judlup
judlup

Reputation: 139

Your code issue is that you put the -- sign after and It should be before(--n) and It also you have declared var n = 50 inside to loop of setInterval, at this way each time that It's executed n variable always is 50, you should to put this varible at the start of yout code.

var n = 50;
var x = setInterval(function() {        
  console.log(--n);
}, 1000);

Upvotes: 2

Ali Faris
Ali Faris

Reputation: 18602

Checkout this: it will stop when x will equals to zero

var x = 100;
    
var handler = setInterval(function(){
    x--;
    console.log(x);

    if(x === 0)
        clearInterval(handler)
} , 1000)

Upvotes: 2

HMR
HMR

Reputation: 39280

And here is one without the need of a global variable but using IIFE:

var x = setInterval(
  (startValue => () => {
    console.log(startValue--);
  })(100),
  1000
);

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386654

You could use a IIFE with a closure about the value. Tha advantage is to use a local variable without polluting the global space.

var x = setInterval(function(n) {
        return function() {
            console.log(n--);
        };
    }(100), 1000);

Upvotes: 6

Related Questions