1

I am trying to call a function after 40 seconds in React native. But it seems no matter what time I set the function calls within 15 to 18 seconds. Have tried several solution but hard luck.

My full code is given below:

export default class OpenLocker extends Component {
  constructor(props) {
    super(props)
    this.state = {
      disable: false,
    }
  }

  openBox() {
    const data = {
      model: this.props.model,
      machine_id: this.props.machine_id,
      locker_id: this.props.locker_id,
    }

    const { model, machine_id, locker_id } = data

    const this_url = window.location.href
    const parse_url = url.parse(this_url, true, true)
    const host = parse_url.protocol + "//" + parse_url.host
    const api_url = `${host}/vendor/locker/open/${model}/${machine_id}/${locker_id}`

    axios
      .get(api_url)
      .then((response) => {
        if (!response.data) {
          alert("Box open failed!")
        } else {
          this.setState({
            disable: true,
          })
          setTimeout(() => {
            this.closeBox(data, host).bind(this)
          }, 40000)
        }
      })
      .catch((error) => {
        alert(error)
      })
  }

  closeBox(data, host) {
    const { model, machine_id, locker_id } = data
    const api_url = `${host}/vendor/locker/close/${model}/${machine_id}/${locker_id}`

    axios
      .get(api_url)
      .then((response) => {
        if (!response.data) {
          alert("Box close failed!")
        } else {
          this.setState({
            disable: false,
          })

          alert("Box opened successfully")
        }
      })
      .catch((error) => {
        alert(error)
      })
  }

  render() {
    return (
      <div>
        <button
          disabled={this.state.disable}
          id="open-box"
          type="button"
          className="btn btn-secondary btn-block text-white"
          onClick={this.openBox.bind(this)}
        >
          Open Box
        </button>
      </div>
    )
  }
}

How to call the function closeBox after 40 seconds or why setTimeout() not working the way I expect? Need your suggestion. Thanks in advance.

Denis Tsoi
  • 9,428
  • 8
  • 37
  • 56
Wahidul Alam
  • 1,216
  • 4
  • 26
  • 56

0 Answers0