我遇到了clearTimeout函数的问题。这两个条件都有效但超时拒绝清除......欢迎任何帮助。时间是300毫秒= params.speed。
**注意:该方法功能齐全且有效。我唯一的问题是清除setTimeout。它会创建一个错误,其中新的非超时烤面包机应用旧的setTimeout。
这意味着如果我在单击超时按钮后3秒内单击非超时按钮,则旧的setTimeout仍然适用于下一个烤面包机。
XMLHttpRequest
答案 0 :(得分:1)
What we have here I believe is a problem of scope,.
Let's say we have a function test
, and when we call it with true
we save the word hello into a var called x. If we then call said function again with false we want it to console.log the value of x, hopefully been the word hello.
We could create function like this->
function test(b) { var x; if (b) x = "hello"; else console.log(x); }
test(true);
test(false); //prints undefined
Now the above based on what the OP has said, is kind of what he's doing with the toaster function. Problem is the above will end up printing undefined
So how do we fix,. All we have to do is move the var x
declaration so it covers the function test
, this will then make the var x
scope global to this instance of test. IOW: every time we call test we want it to see the same instance of x
..
So here is the fixed version.
var x; function test(b) { if (b) x = "hello"; else console.log(x); }
test(true);
test(false); //prints hello
This as expected will print the word hello
..
Now if you think of the function test
been the toaster
function, and the var x
been the timer
var, you can see how the timer
var will end up been undefined the next time you call toaster
..
答案 1 :(得分:0)
You code is not enough to understand where is error, and what you realy want to do. But i think my code will help you to understand where you was wrong.
var timing;
var params = {
timer: true,
speed: 3000
};
function timerToggle() {
clearTimeout(timing);
if (params.timer) {
timing = setTimeout(function() {
alert("timer works");
}, params.speed);
}
}
timerToggle();
$("button").on("click", function() {
params.timer = false;
timerToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click me or wait 3 sec</button>