Search code examples
javascriptsetintervalincrement

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.


Solution

  • 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);
    }