Skip to content

requestAnimationFrame can be used not only for animation

Daisho Komiyama edited this page Nov 16, 2019 · 9 revisions

While I was working on drag & drop sort, I discovered requestAnimationFrame can replace setTimeout function in particular situation.

When you want a function to be called at the last stack, you probably end up using setTimeout with delay 0, This does perfect job for this purpose.

But sometimes, especially when DOM is involved, there could be the cases that a function call fails to update DOM such as <element>.removeAttribute("style") in my case. This is problematic. So you probably add another call after the first call then put it in setTimeout with some delay like 100 millisecond as a fallback in case first call fails. You really want it to updates DOM with no fail.

dd.touchEnd = function () {
    this.removeAttribute("style");  //this fails sometimes
    setTimeout(() => {
        this.removeAttribute("style"); //so this is fallback
    }, 100);
};

This approach works fine but still a bit problematic as well because there are identical 2 calls to make one effect. Not only confusing but also against DRY. You can delete first call then keep one with setTimeout but most of the cases, like with 90% of chance, first call can do its job and that is ideal because user won't see DOM state before function kicks in. When first call fails user can see the unwanted DOM state for 100 millisecond due to setTimeout delay. Of course you can reduce delay to make it unnoticeable but the fewer delay the more chance for fail.

requestAnimationFrame can solve this.

dd.touchEnd = function () {
    requestAnimationFrame(() => {
        this.removeAttribute("style"); //this kicks in immediately then loops until effect is made
    });
};

It looks like requestAnimationFrame is dedicated for animations but what it actually does in the case above is it repeats until the function call makes effect. Repeat won't be made when there's no more effect. It seems perfect for me to solve that kind of corner cases.

Clone this wiki locally