Find the bug in this animation loop.
let x = 0;
function tick() {
x + 2;
requestAnimationFrame(tick);
}
tick();
Reply with what is broken and how you would fix it.
Find the bug in this animation loop.
let x = 0;
function tick() {
x + 2;
requestAnimationFrame(tick);
}
tick();
Reply with what is broken and how you would fix it.
x + 2; is just a math expression that gets thrown away. Nothing ever assigns the new value back into x, so it stays 0 forever.
Fix is to actually mutate x:
let x = 0;
function tick() {
x += 2; // or: x = x + 2
requestAnimationFrame(tick);
}
tick();
Spot the Bug answer: The statement x + 2; computes a value but never assigns it back to x, so x never changes.
The fix:
Change x + 2; to x += 2;
Why:
Expressions like x + 2 are evaluated and discarded unless assigned; without assignment x stays 0 forever, so the animation never actually moves. Using x += 2 updates x on each frame.
:: Copyright KIRUPA 2024 //--