0

s

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

2
  • First thing, why you think the bottle neck comes from interval? Second thing, Im pretty sure the issue is with how you handle the renders, children.map(animateFunc) is NOT how you map children in React (see React docs Children API). You should add codesandbox for more help... Commented Sep 23, 2020 at 9:40
  • Another small advice, you import a npm package with so many dependencies for just calling an interval? github.com/donavon/use-interval/blob/master/src/index.js, better to inline this code Commented Sep 23, 2020 at 9:43

1 Answer 1

1

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);
  }
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.