当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript settimeout reset isn't working

问题描述:

I am trying to reset a timer in javascript but is refuses to work, it just starts another function without stopping the previous one.

time = ((A[Qused].length)*5000) + 10000

refresh = window.setTimeout(function(){timeup(tc,chosen);}, time);

window.clearTimeout(refresh)

refresh = window.setTimeout(function(){timeup(tc,chosen);}, time);

This code is straight from the application and as i explained it doesn't stop the timout, it starts another one though.

Can anyone help please?

thnx in advance

网友答案:

You don't show us much of your code in the real context, but some of the common reasons for not successfully clearing the previous timer are:

  1. Your variable that holds the timer is not a global variable (or in a closure that persists) and thus doesn't survive from one call to the next so when you go to do clearTimeout(refresh), the refresh variable doesn't hold the right value. You can check this by doing a console.log(refresh) before you do the clearTimeout(). If this is your problem, then refresh will probably be undefined.

  2. You're accidentally starting more than one timer thus you're overwriting your refresh variable and your clearTimeout(refresh) only stops that last timer set, not the earlier one. In some forms of code, it's safest to always do clearTimeout() on any prior timer BEFORE you start a new timer to make sure you didn't already have one running or it may make more sense to just check with an if statement if you already have one running.

If you want more specific help, you will need to disclose more details of your ACTUAL code because the four lines of code you have above in that exact sequence and all in the same scope do not have the problem you are experiencing - so obviously there's more to the actual code than you've disclosed.

网友答案:

example of how to clear settimeout

var myVar;

function myFunction()
{
  myVar = setTimeout(function(){alert("Hello")},3000);
}

function myStopFunction()
{
  clearTimeout(myVar);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: