-2

It probably has to do with the 'timer' scope, but I can't get where is the problem. If anyone knows :)

function startTimer() {

    let time = 0;
    progress.style.width = time + '%';

    let timer = function() {

        setInterval(function() {

            time += 0.5;
            progress.style.width = time + '%';
            if (time >= 100) {
                clearInterval(timer);
            }
        }, 100);
    }
    timer();
}
Victofu
  • 53
  • 2
  • 9
  • 5
    You need to pass the argument returned by `setInterval` to `clearInterval`. You are just passing a random function – Alexander Derck Nov 24 '17 at 23:12
  • 1
    Possible duplicate of [Why clearInterval doesn't work on a function](https://stackoverflow.com/questions/45240154/why-clearinterval-doesnt-work-on-a-function) – Sebastian Simon Nov 24 '17 at 23:18

2 Answers2

0

const delay = 300 // time in ms const intervalId = window.setInterval(()=>{ // do stuff here }, delay)

later

window.clearInterval(intervalId)

DrNio
  • 1,936
  • 1
  • 19
  • 25
0

You need to store the instance of setInterval() in order to clear it. You are passing a function into clearInterval()

function startTimer() {

    let time = 0;
    progress.style.width = time + '%';
    // declare instance variable
    let intervalTimer;

    let timer = function() {
         // assign instance
         intervalTimer = setInterval(function() {

            time += 0.5;
            progress.style.width = time + '%';
            if (time >= 100) {
                // clear instance
                clearInterval( intervalTimer);
            }
        }, 100);
    }
    timer();
}
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Just a nit-pick, `setInterval`doesn't return an instance, it returns an id of that particular instance which is an integer. (not my down vote, though). – Teemu Nov 24 '17 at 23:19
  • @Teemu right...just didn't want to get into a long winded explanation of what it actually returned – charlietfl Nov 24 '17 at 23:21
  • Well, a long explanation is better than a misleading answer ..? – Teemu Nov 24 '17 at 23:24
  • @Teemu what is so misleading? The fact that it returns an id is still instance specific – charlietfl Nov 24 '17 at 23:30