3

Say I run a 2-step process during page scrolling, that I'd like to split up for performance reasons (preventing jank). I could use setTimeout:

function foo() {
    // Step 1

    setTimeout(bar, 25);
}

function bar() {
    // Step 2
}

However, I could also use requestAnimationFrame (rAF):

function foo() {
    // Step 1

    requestAnimationFrame(bar);
}

function bar() {
    // Step 2
}

Are there benefits of using rAF instead of a plain timeout? Note that my "Step 2" does not write to the DOM. I just want to yield in order to prevent jank.

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • What do you mean "yield it in order to prevent jank?" If you mean step 2 has a lot of computation/processing, then neither `setTimeout` nor `rAF` will help. See http://stackoverflow.com/questions/12187393/why-javascript-settimeout-is-not-multithreaded – soktinpk Jun 29 '14 at 21:35
  • `requestAnimationFrame` should only be used for animations. It might be throttled differently (depending on the UI) than `setTimeout` or `setImmediate`. – Bergi Jun 29 '14 at 21:57
  • @soktinpk If my JavaScript execution takes too long (e.g. 50ms) during a scroll event, there will be jank. If I use setTimeout, my execution yields and the browser's event loop gets a chance to perform a reflow/paint (= no jank). – Šime Vidas Jun 29 '14 at 23:02
  • 1
    @Bergi That's what the spec states, yes. I'm curious though how rAF performs, compared to setTimeout, for general-purpose computation tasks. It wouldn't be the first time, that an API's misuse has some unexpected positive side-effects :) – Šime Vidas Jun 29 '14 at 23:05
  • @Bergi I have to disagree with you on this one :-) RAF ticks about 60x per second. I sometimes use even ticks to "draw" the animation and odd ticks to do calculations required for the next drawing. No harm done as long as both the drawing and calculation routines are tight and fit within the time allowed. – markE Jun 30 '14 at 22:35
  • 1
    @markE Whoa, interesting approach :) – Šime Vidas Jul 01 '14 at 02:35
  • Possible duplicate of [Is there anything faster than setTimeout and requestAnimationFrame?](https://stackoverflow.com/questions/19906947/is-there-anything-faster-than-settimeout-and-requestanimationframe) – Paul Sweatte May 30 '17 at 05:07
  • 1
    if your step-2 is not related to anything about updating ui or dom then you shouldn't go for rAF. Since rAF execution shouldn't exceed ~10ms ideally or it will cause some jank on UI itself; – Mechanic Feb 26 '20 at 16:00

0 Answers0