reactjs - 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))
};
}
解决方案
推荐阅读
- javascript - 受控 Fluent UI Checkbox 组件的渲染不正确
- gradle - 使用dependsOn从另一个gradle文件调用任务时出错
- mongodb - MongoDB 仅过滤器(如果有)
- facebook - 如何使用 Graph AP 将文件上传到 Facebook Workplace
- html - 使用分离的图像/元素打印到 pdf
- sql - 仅将非空值插入 SQL 表
- c - 成功发送消息后,如何调试 curl 问题(CURLOPT_MAIL_FROM、文本/html 显示)?
- php - 在 MAMP 中,一个 .php 文件正在工作,其他文件会出现 HTTP500 错误
- javascript - 如何检查浏览器是否支持 Nullish 合并运算符 (??)
- c++ - 如何设置 Clang 和 VS Code 以在 Windows 上为 Linux 编译