skip to Main Content

I have this problem where my intervals are not getting removed. When the intervalActive prop from its parent gets changed to false, it should run the function stopPagination, but instead it doesnt. The interval keeps going and it does not stop. Does anybody maybe know what is up with this?

   const startPagination = () => {
        if (!intervalId && intervalActive) {
            const id = setInterval(() => {
                paginate(1);
            }, interval[1] * 1000);
            setIntervalId(id);
        }
    };

    const stopPagination = () => {
        clearInterval(intervalId);
        setIntervalId(null);
    };

    useEffect(() => {
        console.log(intervalActive)
        if (intervalActive) {
            startPagination();
            return () => {
                clearInterval(intervalId);
                setIntervalId(null);
            };
        } else {
            stopPagination();
        }
    }, [intervalActive]);

I tried clearing all intervals, but that did not work and removing the clean up function inside the useEffect creates 2 intervals, one that can be removed and added and another one that I don’t know about.

2

Answers


  1. Chosen as BEST ANSWER
    useEffect(() => {
        if (interval[0]) {
            let intervalId;
            if (intervalActive) {
                intervalId = setInterval(() => {
                    paginate(1);
                }, interval[1] * 1000);
            }
    
            return () => clearInterval(intervalId);
        }
    }, [intervalActive, interval]);
    

  2. Maybe not a direct answer to your question, but I solve this kind of confusing interval mess by just using setTimeout

    const nextPage = () => {
        // your paging code here
    
        // check if we should call the next page again
        if (intervalActive) {
            setTimeout(() => {
                nextPage();
            }, 1000);
        }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search