On button click I am calling Ajax function after every 3min
intervalId = setTimeout(function(){ searchSiteDetailViaAjax() }, 180000);
and on stop button I am stopping this
clearTimeout(intervalId);
intervalId = null;
initially for few time it works fine but then after executing the clearTimeout the timer calls the Ajax function again and again.
On button click I am calling Ajax function after every 3min
intervalId = setTimeout(function(){ searchSiteDetailViaAjax() }, 180000);
and on stop button I am stopping this
clearTimeout(intervalId);
intervalId = null;
initially for few time it works fine but then after executing the clearTimeout the timer calls the Ajax function again and again.
Share Improve this question edited Aug 10, 2017 at 6:33 Aydin4ik 1,9352 gold badges17 silver badges22 bronze badges asked Aug 10, 2017 at 4:04 Dead ProgrammerDead Programmer 1231 gold badge5 silver badges15 bronze badges 3-
Not enough information here. What scope are you defining
intervalId
in? Add more code. – Robby Cornelissen Commented Aug 10, 2017 at 4:06 - Can you post more information? Code sample? – Dan D Commented Aug 10, 2017 at 4:09
- Scope of the intervalId is global. – Dead Programmer Commented Aug 10, 2017 at 5:40
2 Answers
Reset to default 4It sounds like you want to be working with setInterval()
and clearInterval()
. setTimeout()
only runs once, and you said you'd like it to run every 3 minutes, and you'll want to use setInterval()
for that.
setInterval MDN: https://developer.mozilla/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
clearInterval MDN: https://developer.mozilla/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval
Sounds like you may need to call clearTimeout(intervalId);
on click, prior to your setTimeout
call.
It sounds like what is happening is that you queue a function to be executed and by clicking the button again you queue another execution and receive a different handle. Clicking the stop button will not longer be able to clear the previous handles which causes your multiple executions.