1

I had written the following code:

var el = document.getElementsByClassName("header")[0];
function animate() {
    c = 0;
    I = setInterval(adapt,100);
    function adapt() {
        if (c == 255) {
            clearInterval(I);
        }
        else {
            el.style.backgroundColor = "rgb(" + 0 + "," + 0 + "," + c + ")";
            c++;
        }
    }
}

el.addEventListener("click",animate);

If I clicked the header the colour changed gradually from black to blue in a little over 25500 milliseconds as was to be expected, but if you clicked the header again before the animation had fully elapsed strange things would happen. The rate at which the colour changed increased permanently, so if the header was clicked again at any point after that it would take significantly less than 25500 milliseconds for the colour to change completely. It seemed like the animation played faster and faster as you would click more often and in quicker succession.

I have come to learn that I am not as talented as I thought I was and that I simply should have put

let c = 0;
let I = setInterval(adapt,100);

and this indeed fixes the strange behaviour. However I still wonder why this behaviour occurred. All I could find online was that omitting keywords creates global variables and will cause strange errors in general, but not how such errors can occur.

mrmonsieur
  • 304
  • 1
  • 5
  • If you're in [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) or (ideally) a [module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), a ReferenceError is thrown upon attempting to access or assign an undeclared variable. –  Dec 18 '20 at 17:37
  • Without `var` or `let`, `c` is a global var. When you click a 2nd time you now have 2 intervals running. Each one incrementing `c` so it increases faster. – 001 Dec 18 '20 at 17:43
  • @JohnnyMopp thanks that explains the speeding up part. Does that also mean that `I` is set multiple times but cleared only once, so that there are still some intervals running only they do nothing because the maximal blueness has ben reached? – mrmonsieur Dec 18 '20 at 20:05
  • Yes, this would also result in orphaned intervals running constantly in the background since the id will be lost each time `I` is overwritten. – 001 Dec 18 '20 at 20:30

0 Answers0