我对clearTimeout 函数有疑问。两种条件都有效,但超时拒绝清除……欢迎任何帮助。时间为 300 毫秒 = params.speed。
**注意:该方法完全有效且有效。我遇到的唯一问题是清除 setTimeout。它会产生一个错误,即新的非超时 toastr 应用旧的 setTimeout。
这意味着如果我在单击超时按钮后 3 秒内单击非超时按钮,则旧的 setTimeout 仍适用于下一个 toastr 。
// Beginning of function - line below contains the options for the
// toaster method:
// Invoke via - onclick(e, {text: 'This is an alert with a TIMER',
// timer:true, speed: 3500, color: 'dark'})
toaster: function(e, params = {}) {
// Set defaults for params.object options
var setDefaults = function () {
if (e == null) {
e = this.event;
};
if (params.speed == null) {
params.speed = 3500;
};
if (params.timer == null) {
params.timer = false;
};
if (params.color == null) {
params.color = 'light';
};
if (params.text == null) {
params.text = 'This is a default warning'
};
}();
//Apply timer function
timerOn(params.speed); // params.speed = 4500
var timing; // Variable set outside of the timerOn() function
function timerOn () {
if (params.timer) {
timing = setTimeout(function(){
el[0].classList.remove('show-toaster');
console.log('happening');
}, params.speed);
} else {
clearTimeout(timing);
console.log('just cleared timing variable');
}
} // timerOn ends
最佳答案
我认为我们这里有一个范围问题。
假设我们有一个函数 test
,当我们用 true
调用它时,我们将单词 hello 保存到名为 x 的 var 中。如果我们再次使用 false 调用该函数,我们希望它能够 console.log x 的值,希望是单词 hello。
我们可以创建这样的函数->
function test(b) { var x; if (b) x = "hello"; else console.log(x); }
test(true);
test(false); //prints undefined
现在,以上内容基于 OP 所说的内容,这就是他对 toastr 功能所做的事情。问题是上面的内容最终会打印 undefined
那么我们该如何解决呢。我们所要做的就是移动 var x
声明,使其覆盖函数 test
,这将使 var x
作用域对此全局化测试实例。 IOW:每次我们调用 test 时,我们都希望它看到 x
的相同实例..
这是修复后的版本。
var x; function test(b) { if (b) x = "hello"; else console.log(x); }
test(true);
test(false); //prints hello
这正如预期的那样将打印单词 hello
..
现在,如果您认为函数 test
是 toaster
函数,而 var x
是计时器
var,您可以看到下次调用 toaster
时 timer
var 将如何最终变为未定义..
关于javascript - clearTimeout 不起作用 - 尝试了多种变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49439898/