Reputation: 129
So, I have a Redux-action that gets called multiple times throughout my application, essentially what I need is for every time it calls the action it just resets a setInterval for 10 second with the new data that is passed in the action.
export function fetchInterviewer(lastInterviewerId, interviewId, phone) {
setInterval(()=>{
fetchInterviewerLoop(lastInterviewerId, interviewId, phone);
},10000)
}
export function fetchInterviewerLoop(lastInterviewerId, interviewId, phone){
Store.dispatch(interviewerIsLoading(callId));
let p = phone && SystemService.decodePhone(phone);
return {
type: CALL_FETCH_INTERVIEWER,
payload: HttpService.get(`${lastInterviewerId}/interview/${interviewId}/interviewer?phone=${p}`)
}
}
The problem is that every time the fetchInterviewer is called in the application, it doesn't just restart the function, it just creates a new separate looping instance, so I could call the action 10 times and then I'll have 10 different loops.
I've tried multiple different things and I feel like the answer is probably something so small and stupid.
Upvotes: 0
Views: 213
Reputation: 1324
Stop the current interval before setting another one:
let currentInterval = null;
export function fetchInterviewer(lastInterviewerId, interviewId, phone) {
clearInterval(currentInterval);
currentInterval = setInterval(()=>{
fetchInterviewerLoop(lastInterviewerId, interviewId, phone);
},10000)
}
export function fetchInterviewerLoop(lastInterviewerId, interviewId, phone){
Store.dispatch(interviewerIsLoading(callId));
let p = phone && SystemService.decodePhone(phone);
return {
type: CALL_FETCH_INTERVIEWER,
payload:
HttpService.get(`${lastInterviewerId}/interview/${interviewId}/interviewer?phone=${p}`)
}
}
Upvotes: 1
Reputation: 2242
If you don't want to stop the interval you can use an object that references the loop params:
let paramsRef;
let interval;
export function fetchInterviewer(lastInterviewerId, interviewId, phone) {
paramsRef = {lastInterviewerId, interviewId, phone}
if(!interval){
interval = setInterval(()=>{
const {lastInterviewerId, interviewId, phone} = paramsRef
fetchInterviewerLoop(lastInterviewerId, interviewId, phone);
},10000)
}
}
export function fetchInterviewerLoop(lastInterviewerId, interviewId, phone){
Store.dispatch(interviewerIsLoading(callId));
let p = phone && SystemService.decodePhone(phone);
return {
type: CALL_FETCH_INTERVIEWER,
payload: HttpService.get(`${lastInterviewerId}/interview/${interviewId}/interviewer?phone=${p}`)
}
}
Upvotes: 1