-1

I am trying to create a setInterval function that checks to see whether an element exists after a click event. The setInterval works fine but I cant get it to clear when using clearInterval. So what I am trying to achieve is that once the element exists it should stop running the setInterval function. However the function keeps running once the element has loaded on the page. My code is below

editStore()?.addEventListener('click', () => {
      const firstInterval = () =>
        setInterval(function () {
            intervalFunc()
        }, 500)
      const intervalFunc = () => {
        if (newSearchStore()) {
          console.log('new search store')
          clearInterval(firstInterval())
        }
      }
      firstInterval()
    })

What am I doing wrong here? Any help would be really appreciated.

Thanks in advance!

user16732475
  • 15
  • 1
  • 6
  • 2
    Calling `firstInterval()` creates a new interval. `clearInterval(firstInterval())` is therefor a no-op... – Andreas Aug 05 '22 at 09:53
  • 1
    Calling `setInterval()` will give you the ID you need in order to cancel the interval started by the function. And each call to `setInteval()` gives you a new ID. Your code is (simplified) `setInterval(); clearInterval(setInterval());` – VLAZ Aug 05 '22 at 09:53

1 Answers1

0

You are creating two different intervalID's by running firstInterval two times.

editStore()?.addEventListener('click', () => {
  // declare variable
  let intervalID;
  const firstInterval = () => {
    // assign setInterval's result
    intervalID = setInterval(function () {
      intervalFunc()
    }, 500)
  }
  const intervalFunc = () => {
    if (newSearchStore()) {
      console.log('new search store')
      // use variable to clear interval
      clearInterval(intervalID)
    }
  }
  firstInterval()
})
Konrad
  • 21,590
  • 4
  • 28
  • 64