admin管理员组

文章数量:1319014

When I try to clearTimeout(), the timeout just continues. Code:

function autoSlides(x) {
    var timeOut;
    if (x == 1) {
        plusSlides(1);
        document.getElementById("switch").onclick = function () { autoSlides(2) };
        timeOut = setTimeout(function () { autoSlides(1) }, 4000);
    } else if (x == 2) {
        clearTimeout(timeOut);
        document.getElementById("switch").onclick = function () { autoSlides(1) };
    }
}

When I try to clearTimeout(), the timeout just continues. Code:

function autoSlides(x) {
    var timeOut;
    if (x == 1) {
        plusSlides(1);
        document.getElementById("switch").onclick = function () { autoSlides(2) };
        timeOut = setTimeout(function () { autoSlides(1) }, 4000);
    } else if (x == 2) {
        clearTimeout(timeOut);
        document.getElementById("switch").onclick = function () { autoSlides(1) };
    }
}
Share Improve this question asked May 12, 2017 at 18:12 TaabklTaabkl 1232 silver badges10 bronze badges 1
  • 1 timeOut is not in scope for your else if block. You initialize it at function scope but assign it only in your if block. – Elliot Rodriguez Commented May 12, 2017 at 18:13
Add a ment  | 

3 Answers 3

Reset to default 5

That's because you're declaring timeOut inside of the function. That means that you aren't using the same value you thought you saved earlier.

function autoSlides(x) {
  var timeOut; // Initialized to `undefined`
  if (x === 1) {
    timeOut = setTimeout(function() {
      console.log('Look, the timeout finished');
    }, 1000);
  } else if (x === 2) {
    // Remember: this is a new timeout variable
    // So this really means `clearTimeout(undefined)`
    clearTimeout(timeOut);
  }
}

autoSlides(1);
autoSlides(2);

What you need to do is save the timeout ID somewhere outside of the function.

var timeOut; // Won't be reset every time the function is called
function autoSlides(x) {
  if (x === 1) {
    timeOut = setTimeout(function() {
      console.log('Look, the timeout never finishes');
    }, 1000);
  } else if (x === 2) {
    // The value was saved last time
    clearTimeout(timeOut);
    console.log('cleared the timeout');
  }
}

autoSlides(1);
autoSlides(2);

timeOut is a variable local to autoSlides.

autoSlides has an if statement so it will either:

  • Assign a value to timeOut
  • Try to use timeOut to clear a timeout

Since it never does both, the value of timeOut will always be undefined in the second case.

If you want to reuse the variable across multiple calls to the autoSlides function then you need to declare it outside, not inside, autoSlides.

You can assign "timeout" to outside of the function scope. One option is to attach it to the global "window" object if your using client-side javascript:

window.timeOut = setTimeout(function () { autoSlides(1) }, 4000);

clearTimeout(window.timeOut);

本文标签: jscriptJavascript clearTimeout() not workingStack Overflow