首页 > 解决方案 > setTimeOut is not delayed second time but works correctly first

问题描述

I have an api call where its results are being dispatched through redux state update. I have added a setTimeOut after fetching results so that results are dispatched only after a delay of 15 seconds. For first api call the setTimeOut will get executed after 15 seconds but when second time api call is being made setTimeOut is executed right away.

I have seen the posts where it says it will run only once. But its supposed to run again when called right ?

What I understood is that setTimeOut will create a delay of desired time and after that delay it will run and stop there. But when called again it would again create a delay and excuse after that right ?

This is my code

 export const getVenuesBonusOffer = (venueId, uid, accessToken) => {
  return (dispatch, getState) => {
    let header = getHeader(
      CONTENT_TYPES.application_URLencoded,
      uid,
      accessToken
    );
    let url = VENUE_BONUS_OFFER + venueId;
    __DEV__ && console.log("url: ", url, " header: ", header);
    _GET(url, header)
      .then(res => res.json())
      .then(res => {
        //__DEV__ && console.log("Res for getVenuesBonusOffer: ", res);
        if (res.message === API_RESPONSE_MESSAGE.NO_BONUS_OFFER_EXIST) {
          //showAlert("OOPS", res.message, "danger", false);
          dispatch(venuesBonusOfferNotExist());
        } else {
          this.timeoutid = setTimeout(() => {
            __DEV__ && console.log("timeout");
            dispatch(venuesBonusOfferExist(res.data));
            clearTimeout(this.timeoutid);
          }, 15000);
        }
      })
      .catch(err => {
        __DEV__ && console.log("err for getVenuesBonusOffer: ", err);
      });
  };
};

EDIT 1

please note this is not called from class but its within an const like export const something

EDIT 2

from class called RunAR.js the above method is called. Called from componentWillReceiveProps

componentWillReceiveProps(nextProps, nextState) {
    if (this.props.venuesBonusOfferDuration === 0) {
      this.subscribe.unsubscribe();
    }
    if (nextProps.showBonusObj) {
      let milliseconds = nextProps.venuesBonusOfferDuration * 1000;
      this.source = timer(milliseconds);
      const subscribe = this.source.subscribe(val => {
        this.props.hideBonusOffer();
        const timerForBonusApi = bonusApiTimer.subscribe(val => {
          console.log("caling timer");
          this.props.getVenuesBonusOffer(
            this.props.venues.venues.id,
            this.props.uid,
            this.props.accessToken
          );
        });
      });
    }
  }

function mapDispatchToProps(dispatch) {
  return {
    hideUserMenu: () => dispatch(hideUserMenu()),
    showingVenueLoaderinAR: data => dispatch(showingVenueLoaderinAR(data)),
    isPopupActiveFun: data => dispatch(isPopupActiveFun(data))
  };
}

标签: reactjsreact-nativesettimeout

解决方案


推荐阅读