Home > Mobile >  How to use setInterval and setTimeout with React hooks
How to use setInterval and setTimeout with React hooks

Time:11-29

  • I want to loop through an array of strings

  • When a new string, from the array, is selected I want to print out a substring of the selected string every 0.1 second

  • After the entire string is printed I want to pause and then select the next string in the array

  • Repeat

    eg ['one', 'two'] output: o on one // pause 1 second t tw two // pause 1 second o on one // pause 1 second

I have tried this but it only loops through once

  useEffect(() => {
    let i = 0

    function increment() {
      i  
      console.log(i)
    }

    const incrementTimer = setInterval(increment, 100)

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

CodePudding user response:

use two timeouts instead of interval

    const incrementTimer = setInterval(printInInterval, 100)


function printInInterval(){
  ['one', 'two'].forEach((item) => {
      setTimeout(() => {printVal(item)}, 1000)

  })
}

function printVal(word){
   word.split("").forEach((w) => {
      setTimeout(() => {
        console.log(w)
      }, 100)

   })
}

CodePudding user response:

I created a codesandbox link: https://codesandbox.io/s/recursing-bash-hkmqrc?file=/src/App.js

This is done by rxjs as you are dealing with time related actions. rxjs is the best tool. After you reload the page, it will start to log values as you expect in 1s.

Can you please let me know if the result is what you want? Thanks.

  • Related