How to setTimout on react component

Asked
Active3 hr before
Viewed126 times

10 Answers

componentreact
90%

“` useEffect(() => { const timer = setTimeout(() => { setCountInTimeout(count); // count is 0 here }, 3000); setCount(5); // Update count to be 5 after timeout is scheduled return () => clearTimeout(timer) }, [count]); “`,And an example of clearing setTimeout inside of a React Class component:,A setTimeout timer must be cleared and handle properly, otherwise, you may experience adverse side effects in your code.

useEffect(() => {
   const timer = setTimeout(() => {
      console.log('This will run after 1 second!')
   }, 1000);
   return () => clearTimeout(timer);
}, []);
load more v
88%

Your code scope (this) will be your window object, not your react component, and that is why setTimeout(this.setState({position: 1}), 3000) will crash this way.,setTimeout takes the location of the function and keeps it in the context.,Connect and share knowledge within a single location that is structured and easy to search.

Do

setTimeout(
   function() {
      this.setState({
         position: 1
      });
   }
   .bind(this),
   3000
);

You can also use ES6 arrow functions to avoid the use of this keyword:

setTimeout(
   () => this.setState({
      position: 1
   }),
   3000
);
load more v
72%

We can use the setTimeout function in React hooks just like how we use in JavaScript.,In this tutorial, we are going to learn about the usage of setTimeout function in React hooks with the help of examples.,In this example, we have used the setTimeout function inside useEffect hook to update the count value from 0 to 1 after a 3000 milliseconds (or 3 seconds) is finished.

setTimeout(() => {
   console.log('you can see me after 2 seconds')
}, 2000);
load more v
65%

The component simulates a light switch. It has a state on which is true or false. When the button is clicked it waits 5000ms before switching the on state.,When the wrapped component is unmounted, any lingering timers will be canceled automatically.,React Timeout is a higher order component for React and React Native providing the wrapped component with safe versions of

npm install--save react - timeout
import ReactTimeout from 'react-timeout'
import React from 'react'
import ReactTimeout from 'react-timeout'

class LightSwitchExample extends React.Component {
  state = {
    on: false
  }
  toggle = () => {
    this.setState({ on: !this.state.on })
  }
  handleClick = (e) => {
    this.props.setTimeout(this.toggle, 5000) // call the `toggle` function after 5000ms
  }
  render () {
    return (
      <div style={{ backgroundColor: (this.state.on ? 'yellow' : 'gray') }}>
        <button onClick={this.handleClick}>Click me!</button>
      </div>
    )
  }
}
export default ReactTimeout(LightSwitchExample)
const Example = (props) => {
  return (
    <button
      onClick={() => props.setTimeout(..)}>Click me!</button>
  )
}
export default ReactTimeout(Example)
@ReactTimeout
class Example extends React.Component {
  render () {
    return (
      <button
        onClick={() => this.props.setTimeout(..)}>Click me!</button>
    )
  }
}
import ReactTimeout from 'react-timeout/native' // only for react-native 0.17 or below
load more v
75%

Pretag
 Pretag team - issue, fix, solve, resolve
40%

For this guide, I'll create a very minimal sign-in form that will have two input fields: email and password.,Our component state would look as follows:,We will set the error state respectively for each input field.

1 this.state = {
   2 values: {
      3 email: "",
      4 password: ""
      5
   },
   6 errors: {
      7 email: "",
      8 password: ""
      9
   }
   10
};
load more v
22%

The first, setTimeout, will perform the function once after the time you specified has passed.,The second function, setInterval, performs the function after the time you specified has passed until you tell it to stop.,Have tight control over the situations where it is rendered

Pretag
 Pretag team - issue, fix, solve, resolve
60%

The clearTimeout() and clearInterval() methods must clear the entry identified as handle from the list of active timers of the WindowOrWorkerGlobalScope object on which the method was invoked, if any, where handle is the argument passed to the method. (If handle does not identify an entry in the list of active timers of the WindowOrWorkerGlobalScope object on which the method was invoked, the method does nothing.),While clearTimeout won’t have any effect if the timer is complete, if the component that uses handleCopy unmounts before setTimeout finishes, the return of the useEffect will ensure there is no memory leak. ,Do a quick search and you’ll find many people saying that with setTimeout there is no need to call clearTimeout unless we want to end the setTimeout early.

import {
   useState
} from "react";
import copy from "copy-to-clipboard";

export const useClipboard = () => {
   const innerText = “Copy to clipboard”;

   const [labelText, setLabelText] = useState(innerText);

   const handleCopy = (text: string) => {
      copy(text);
      setLabelText("Copied!");
      setTimeout(() => setLabelText(innerText), 2000);
   };

   return {
      labelText,
      handleCopy
   };
};
load more v
48%

Using these scheduling methods with reactJs is straightforward. However, we need to be aware of a few small gotchas to use them effectively. In this article, we will explore the usages of setInterval and setTimeout methods with reactJS components. ,Just like the setInterval method, we will use the setTimeout method inside the useEffect hook. We will also clear the timer when the component unmount.,Let us build a simple Real-time Counter and Task Scheduler to demonstrate the usages.

Pretag
 Pretag team - issue, fix, solve, resolve
23%

For testing the interval function callback code, we use runPendingTimers. If we use something like runAllTimers to wait for all the timers to run, then it will result in an infinite loop in setInterval. ,There is no need to wait for the interval time to be over to test the callback function code. We can use fake timers to advance the time. Following is the code to use the fake timers.,In the above function, there are two functions - setTimeoutFn which starts the setTimeout and setIntervalFn which starts the setInterval. We have a state variable that is being updated in the callback function of the setTimeout and setInterval. Let us see the unit test code using the enzyme.

When we are using timer functions like setTimeout or setInterval, it is difficult to test them as the callback function is called after a certain time is passed. In async http API calls, we can mock the API call and test the success and error condition. In async functions like setTimeout or setInterval, we can also mock the timing to make it speed faster instead of waiting for it to over. Let us see how.

import React, { Component } from "react";
class Timers extends Component {
  constructor() {
    super();
    this.state = {
      index: 0
    };
    this.setTimeoutFn = this.setTimeoutFn.bind(this);
    this.setIntervalFn = this.setIntervalFn.bind(this);
  }
  setTimeoutFn() {
    setTimeout(() => {
      this.setState({
        index: 1
      });
    }, 1000);
  }
  setIntervalFn() {
    setInterval(() => {
      this.setState({
        index: this.state.index + 1
      });
    }, 1000);
  }
  render() {
    return <div></div>;
  }
}
export default Timers;
load more v

Other "component-react" queries related to "How to setTimout on react component"