最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - settimeout executes multiple times - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 4

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/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.

发布评论

评论列表(0)

  1. 暂无评论