Reputation: 3432
I use setInterval
in my code to make my slider work. It should change image each 5 second . But I see that when I use it , it consume new memory all the time . How can I use setInterval
without consuming new memory ?
const Slider = ({ children, sliderIndex, setSlideIndex }) => {
const classes = useStyles()
useInterval(() => {
setSlideIndex((sliderIndex + 1) % children.length)
}, 5000)
const animateFunc = useCallback(
(child, indx) => {
return (
(indx === sliderIndex && (
<div className={classes.root} key={indx}>
{children[sliderIndex].image}
</div>
)) ||
null
)
},
[children, classes.root, sliderIndex]
)
return children.map(animateFunc)
}
i use @use-it/interval hook for it https://www.npmjs.com/package/@use-it/interval
Upvotes: 0
Views: 524
Reputation: 1188
It seems unlikely to me that the interval is actually causing your issue here.
Below is a snippit that will run for two minutes - printing a new line to the console each second. Take a look at the memory usage over time in this page - it won't grow. You can even add a heavy for/while function into it if you like. I think your issue is elsewhere in your code and there are some good comments above to follow up.
let n = 1;
let myInterval = setInterval(function(){ console.log("hello number:" + n++); shouldIStop(120) }, 1000);
function shouldIStop(maxCount){
if (n >= maxCount){
clearInterval(myInterval);
}
}
Upvotes: 1