Skip to content
Advertisement

Increment Interval – JS

This is probably well simple but I just can’t work it out
When I run this…

function logCountUp(){
        let a = 0;
        while(a < 10)
        {
            a+=1;
            console.log(a);
        }
    }
    setInterval(logCountUp,2000);

it returns all numbers,
I want each number every 2 seconds.
I tried wrapping the setInterval around the a++ but it then ignored the while.
It’s proper stumped me.

Thanks in advance.

Advertisement

Answer

setInterval repeatedly calls a function each period of time, so, in this case, when a reaches the max value (9), we stop the interval using clearInterval:

let a = 0;
const interval = setInterval(logCountUp, 2000);
function logCountUp() {
  a+=1; console.log(`${a}`);
  if(a === 9) clearInterval(interval);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement