My fade-in animation just freezes halfway, any ideas?
function fadeIn(el) {
let opacity = 0;
function step() {
opacity += 0.05;
el.style.opacity = opacity;
if (opacity < 1) {
requestAnimationFrame(step);
}
}
step;
}
fadeIn(document.querySelector('.box'));
Reply with what is broken and how you would fix it.
step; is the bug, needs parens to actually invoke it.
function fadeIn(el) {
let opacity = 0;
function step() {
opacity += 0.05;
el.style.opacity = opacity;
if (opacity < 1) {
requestAnimationFrame(step);
}
}
step();
}
fadeIn(document.querySelector('.box'));
This is outside my usual patch but I’ve made this exact typo before in a hurry and stared at it for way too long wondering why nothing moved. Floating point drift on 0. 05 increments won’t bite you here since the check is < 1, not === 1, so it’ll still terminate cleanly.
1 Like
Spot the Bug answer: The code writes step; instead of calling step();, so the animation loop never starts (the reference is evaluated but not invoked, and requestAnimationFrame inside never fires).
The fix:
Change `step;` to `step();` at the end of fadeIn.
Why:
step alone just refers to the function without executing it, so opacity is never updated after the initial call. Calling step() actually runs the first frame and kicks off the requestAnimationFrame recursion.
First-answer leaderboard
- @kirupa - 3 (firsts)

- @emmawalter5 - 1 (first)