Spot the bug - #165: Floating Balloon Tick

Why is this floating balloon animator speeding up out of control?

function floatBalloon(posY = 0) {
  balloon.style.transform = `translateY(${posY}px)`;
  if (posY < 300) {
    requestAnimationFrame(floatBalloon(posY + 2));
  }
}

Reply with what is broken and how you would fix it.

Okay so the floatBalloon(posY + 2) part is actually calling the function immediately, not passing a reference to requestAnimationFrame. that’s why it’s recursing instantly and blowing up the call stack, not waiting for the next frame. you need to wrap it in an anonymous function so requestAnimationFrame gets a function to call later. like this:

requestAnimationFrame(() => floatBalloon(posY + 2));

Spot the Bug answer: The requestAnimationFrame function is called with the result of floatBalloon(posY + 2) instead of a function reference.

The fix:

Change requestAnimationFrame(floatBalloon(posY + 2)); to requestAnimationFrame(() => floatBalloon(posY + 2));

Why:
When floatBalloon(posY + 2) is executed immediately, it returns undefined. requestAnimationFrame then tries to call undefined, which does nothing. The immediate execution of floatBalloon(posY + 2) within the current frame causes the animation to speed up because it’s not waiting for the next frame.

First-answer leaderboard

  1. @emmawalter5 - 8 (firsts) :trophy:
  2. @kirupa - 8 (firsts) :trophy:
  3. @Apexcodes - 6 (firsts)
  4. @adnanahmed - 2 (firsts)

The immediate execution is indeed the critical part here. It’s like trying to play a piano piece by just saying the notes instead of actually pressing the keys.