pqina / tick

⏱ A counter component to render different countdown styles with
MIT License
83 stars 8 forks source link

dangling requestAnimationFrame loop causes high CPU usage, even after it is destroyed #4

Open paulovieira opened 2 years ago

paulovieira commented 2 years ago

Hello and congratulations for this nice and sophisticated library!

I'm using a simple flip countdown (using one of the examples from pqina/flip). The countdown is created and destroyed dynamically. However after being destroyed (which is done with tickInstance.destroy()) I noticed an unusual high CPU usage.

After some investigation I found the problem: in the presentTick function in https://github.com/pqina/tick/blob/master/src/core/js/utils.js, draw is called recursively using requestAnimationFrame. This loop doesn't stop, even after the tick instance is destroyed.

I solved the problem with a quick and dirty monkey-patch: 1) after calling tickInstance.destroy(), set tickInstance._IS_DESTROYED = true; 2) in presentTick, check if the instance is destroyed before calling requestAnimationFrame, that is:

    var draw = function draw() {
        instance.baseDefinition.presenter.draw();

        if (instance._IS_DESTROYED) { return; }

        requestAnimationFrame(draw);
    };

The CPU is now back to 0 as expected, so I'm pretty sure the problem was here.

Hopefully this problem can be solved in a future release.

Thanks for your time.