Μετάβαση στο κύριο περιεχόμενο
← ⚡ JavaScript & the browser·Ενότητα C9 · Μάθημα 6
ΕργασίαBuild counter = 0. Inside step(): counter++; if counter < 5 schedule another RAF; else log 'done at ' + counter. Kick off with RAF. Output should end with 'done at 5'.

requestAnimationFrame — smooth animation

100 XP8 min
Θεωρία

The right way to animate

setInterval(fn, 16) runs your function regardless of whether the browser can render. requestAnimationFrame(fn) runs ONCE before the next paint — at most 60 times per second on a 60Hz display, slowed automatically when the tab is backgrounded.

let pos = 0;
function step(timestamp) {
  pos += 1;
  if (pos < 100) {
    requestAnimationFrame(step);
  }
}
requestAnimationFrame(step);

What you get

  • The callback receives the timestamp (DOMHighResTimeStamp).
  • No work in background tabs — the browser pauses RAF when the tab isn't visible.
  • Synced to display refresh — never partial frames.

Cancelling

requestAnimationFrame returns an id. cancelAnimationFrame(id) aborts the queued tick.

const id = requestAnimationFrame(step);
cancelAnimationFrame(id);

When to use setInterval anyway

Polling a server every 30 seconds — that's not animation. RAF is overkill. Use setInterval/setTimeout for that.

🔒

Εγγράψου για να αρχίσεις να προγραμματίζεις

Η θεωρία είναι ανοιχτή για όλους. Ο επεξεργαστής, η ζωντανή προεπισκόπηση και ο έλεγχος ξεκλειδώνουν με 7-ήμερη δωρεάν δοκιμή — απαιτείται κάρτα.

Εγγραφή — δωρεάν δοκιμή →

Τα πρώτα 10 μαθήματα κάθε διαδρομής είναι δωρεάν. Δεν χρειάζεται κάρτα.

← ΠροηγούμενοΕπόμενο μάθημα →

Μια συμβουλή Python ή web την ημέρα — με email

Σύντομο, γραμμένο στο χέρι, χωρίς spam. Διαγραφή με ένα κλικ.