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 yourelse if
block. You initialize it at function scope but assign it only in yourif
block. – Elliot Rodriguez Commented May 12, 2017 at 18:13
3 Answers
Reset to default 5That'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
版权声明:本文标题:jscript - Javascript clearTimeout() not working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742051875a2418100.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论