简体   繁体   中英

settimeout executes multiple times

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.

It 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.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

clearInterval MDN: https://developer.mozilla.org/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM