简体   繁体   English

settimeout执行多次

[英]settimeout executes multiple times

On button click I am calling Ajax function after every 3min 点击按钮我每3分钟后调用一次Ajax函数

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. 最初几次它工作正常,但在执行clearTimeout后,定时器一次又一次地调用Ajax函数。

It sounds like you want to be working with setInterval() and clearInterval() . 听起来你想要使用setInterval()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. setTimeout()只运行一次,你说你希望它每3分钟运行一次,你就会想要使用setInterval()

setInterval MDN: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval 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 clearInterval MDN: https//developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval

Sounds like you may need to call clearTimeout(intervalId); 听起来你可能需要调用clearTimeout(intervalId); on click, prior to your setTimeout call. 点击,在你的setTimeout调用之前。

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. 单击停止按钮将无法再清除导致多次执行的先前句柄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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