search

Home  >  Q&A  >  body text

How to display a message every 5 seconds in ReactJS

<p>I have an array of messages and I want to display each message in the array in the Header component of my React page. </p> <p>const array = ['a', 'b', 'c', 'd'];</p> <p>I want to display each message in a </p><p> tag and at the same time I need a clear timeout function to prevent the time from speeding up after each click and it should switch to after 5 seconds Next message, please can someone help me. </p>
P粉464208937P粉464208937573 days ago552

reply all(1)I'll reply

  • P粉037450467

    P粉0374504672023-08-19 00:25:04

    For a simple loop over an array, you can do this:

    const array = ['a', 'b', 'c', 'd'];
    
    counter = 0;
    const interval = setInterval(() => {
      console.log(array[counter % array.length]); //例如 "a", "b"
      //你可以对返回值做任何操作(将其放入a标签中)
      counter++;
    }, 5000);
    

    To clear the interval, you can do this:

    clearInterval(interval);
    

    I'm not sure what you want to do in the click event. Please provide further information.

    reply
    0
  • Cancelreply