Home > Mobile >  How to use setInterval with a pause between loops?
How to use setInterval with a pause between loops?

Time:11-30

In my react component, once the component loads, I am trying to repeat a task every 100ms and after 3 repetitions pause for 1 second. Then repeat this pattern indefinitely.

I want to achieve this output:

1 // pause 100ms
2 // pause 100ms
3 // pause 100ms
// pause 1second
... repeat

I tried something like this

useEffect(() => {
  let i = 0

  function increment() {
    if (i === 3) {
      // i = 0
      // restart timer?
      // return?
    }
    i  
    console.log(i)
  }

  const incrementTimer = setInterval(increment, 100)

  setInterval(() => {
    clearInterval(incrementTimer)
  }, 1000)
}, [])

CodePudding user response:

You can achieve this via setTimeout.

useEffect(() => {
  let i = 0
  let incrementTimer
  function increment() {
    if (i === 3) {
      // i = 0
      // restart timer?
      // return?
    }
    i  
    console.log(i)
     incrementTimer = setTimeout(increment, 100)
  }

  increment()

  setInterval(() => {
    clearInterval(incrementTimer)
  }, 1000)
}, [])

CodePudding user response:

First you need to define a state to determine at which level the component is.

const [levelIndex, setLevelIndex] = useState(0);

Then create an array for execution time at each level (This is For the case that you are looking for, it can be changed depending on what time spans are needed or which pattern a user wants).

const intevalExecutionTime = [100,100,100,1000];

Next create a useEffect hook like this:

useEffect(() => {
  const timer = setInterval(() => {
    if(levelIndex === 3){
      setLevelIndex(0);
      console.log(`one second paused`);
    }
    else{
      setLevelIndex(levelIndex 1);
      //the task that you want to be done.
      console.log('task is done.')
    }
    clearInterval(timer);
  }, intevalExecutionTime[levelIndex])
}, [levelIndex]);

This hook callback will set an interval based on the interval execution time level. Every time the setInterval callback is triggered the older interval object will be removed and it changes the levelIndex and the useEffect callback will be called once again.

  • Related