0

Try to build setTimeout() in React js. I setup this in componentnDidMount() but it works only once. Not working loop.

The code:

  componentDidMount() {
    setTimeout(console.log("hello"), 1000);
  }

The warning show:

[Violation] 'setInterval' handler took 99ms

How can I repeat this function?

k10a
  • 947
  • 2
  • 11
  • 30
  • 2
    Firstly, the first argument to `setTimeout` is a *function*, not a *function call*. So like `setTimeout(() => console.log("hello"), 1000);`. Secondly, `setTimeout` doesn't loop, you're thinking of `setInterval` – Jayce444 Apr 02 '20 at 02:37
  • Does this answer your question? [setTimeout() in componentDidMount() does not work](https://stackoverflow.com/questions/49276487/settimeout-in-componentdidmount-does-not-work) – Marcelo Batista Apr 02 '20 at 02:37
  • Answers are below, but remember to save the return value of the `setTimeout`/`setInterval` in order to call `clearTimeout`/`clearInterval` when the component unmounts so you don't have any accidental "access of ... unmounted..." errors. – Drew Reese Apr 02 '20 at 03:02

2 Answers2

0

setTimeout(function, waitTime)

when you pass a function to the setTimeout method, the method waits for a specified amount of time waitTime, and it calls the function function. But passing in console.log('hello') only simply logs out "hello", but does not return anything and thus does not actually pass a function or callable into the method.

Many ways to go around this:

setTimeout(function(){console.log("hello");},1000); //passes an actual function
setTimeout(()=>{console.log("hello");},1000); //lambda, passes an actual function
setTimeout(()=>console.log("hello"),1000); //same here

Also, if it was supposed to be repeated over intervals, then use setInterval (same arguments as setTimeout).

Kino Bacaltos
  • 373
  • 1
  • 2
  • 16
0

Use setInterval(). Here is a good explanation: setTimeout or setInterval?

setTimeout()

setTimeout() only execute one time when the time reached.

setInterval()

setInterval() is an interval based function and execute repeatedly when the interval is reached.

And examples for setTimeout() and setInterval(). Hope it helps.

yyc
  • 288
  • 1
  • 4
  • 16