menu

Questions & Answers

Unexpected behaviour of setInterval function (interval keeps on decreasing)

Don't know why interval keeps on decreasing.

import React, { useState } from 'react';
import styled from 'styled-components';
import p1 from '../images/slider-badag.jpg';
import p2 from '../images/slider-badging.jpg';
import p3 from '../images/slider-scale.jpg';
import p4 from '../images/slider-scales.jpg';

const ImgSlider = () => {
    const imgArr = [p1, p2, p3, p4];
    const [index, setIndex] = useState(0);
    setInterval(() => {
        if (index < imgArr.length-1) {
            setIndex(index + 1);
        }
        else setIndex(0);
    }, 3000);
    return (
        <>
            <Wrapper imgUrl={imgArr[index]}>
                {console.log(index)}
            </Wrapper>
        </>
    );
}
const Wrapper = styled.div`
    border: 1px solid red;
    height: calc(160%/3);
    background-image: url(${(props) => props.imgUrl});     
    z-index: 10;
    overflow: hidden;
`

export default ImgSlider;

Here I am trying to make an image slider here. In every 3 seconds the image changes due to setInterval function. But after sometime the images start to change rapidly that is in less than 1 second interval only (in milliseconds!). Why is this happening? Please help me.

Comments:
2023-01-21 23:25:08
You're creating a new interval every time the component rerenders. You should only create one when the component mounts. (You should also clean up the interval when it unmounts.)
2023-01-21 23:25:08
Ok so I wrapped setInterval function inside useEffect and also cleared it inside useEffect. useEffect has one dependency "index". It works. This is what you were saying right?
Answers(0) :