flowbite icon indicating copy to clipboard operation
flowbite copied to clipboard

Carousel doesn't stop if calling cycle several times before calling pause

Open manutiedra opened this issue 6 months ago • 1 comments

Describe the bug If you have a carousel and call several times the cycle method, then calling the pause method does not work

Expected behavior it doesn't matter how many time you call cycle. If after a few calls to cycle you call pause, the carousel should pause

Additional context The cycle method is:

/**
 * Set an interval to cycle through the carousel items
 */
Carousel.prototype.cycle = function () {
    var _this = this;
    if (typeof window !== 'undefined') {
        this._intervalInstance = window.setInterval(function () {
            _this.next();
        }, this._intervalDuration);
    }
};

As you can see, it doesn't check if it already had a called setInterval before, so calling it several times will make impossible to stop the timer. The proper fix can be something like this:

/**
 * Set an interval to cycle through the carousel items
 */
Carousel.prototype.cycle = function () {
    var _this = this;

    if (this._intervalInstance) {
        clearInterval(this._intervalInstance);
        this._intervalInstance = null;
    }

    if (typeof window !== 'undefined') {
        this._intervalInstance = window.setInterval(function () {
            _this.next();
        }, this._intervalDuration);
    }
};

Please fix it

/**
 * Clears the cycling interval
 */
Carousel.prototype.pause = function () {
    if (this._intervalInstance) {
        clearInterval(this._intervalInstance);
        this._intervalInstance = null;
    }
};

manutiedra avatar Jun 01 '25 19:06 manutiedra

Also, it would be good to call clearInterval in the destroy method or call to pause

manutiedra avatar Jun 01 '25 21:06 manutiedra

Even after destroy() the cycle()ing will still continue forever. Putting a console log in options onChange() and you'll see it continues to log even if you destroy. Currently, I'm pausing the carousel when the component that use it is destroyed itself, but I know the code is in limbo somewhere in its guts.

andrewevans avatar Jul 17 '25 08:07 andrewevans