【问题标题】:resetting timeout javascript重置超时javascript
【发布时间】:2016-07-09 06:18:10
【问题描述】:
当用户单击元素时,它应该启动超时并将开始时间设置为 true。然后,如果用户在计时器处于活动状态时再次单击元素,它应该清除超时并重新启动超时。但是,我仍然从第一个开始获取控制台,并启动了以下超时。 cleartimeout 不应该只给我留下一个,最后一个创建的吗?我已经在这里How to reset timeout in Javascript/jQuery? 尝试过这个问题的例子。
toggleCard: function(card){
var Timer = null;
if(this.startTime){
console.log('already activated');
window.clearTimeout(Timer);
this.startTime = false;
}
this.startTime = true;
var Timer = setTimeout(function(){
// this.taskCard = false;
// this.classCard = true;
console.log('old timer')
}.bind(this), 5000);
【问题讨论】:
标签:
javascript
jquery
time
vue.js
【解决方案1】:
定义全局变量,例如
var myTimeOut = 0;
然后在你的方法调用clearTimeout
toggleCard: function(card){
clearTimeout(myTimeOut);
this.startTime = true;
myTimeOut = setTimeout(function(){
// this.taskCard = false;
// this.classCard = true;
console.log('old timer')
}.bind(this), 5000);
【解决方案2】:
这样做:
toggleCard: function(card) {
window.Timer = null; // <-----------declare timer globally here
if (this.startTime) {
console.log('already activated');
window.clearTimeout(Timer); // <------- clear here if it is.
this.startTime = false;
}
Timer = setTimeout(function() { // <-------assign the setTimeout here
this.startTime = true; // <---------It has to be here.
// this.taskCard = false;
// this.classCard = true;
console.log('old timer')
}.bind(this), 5000);
【解决方案3】:
我认为这段代码应该满足您的要求。
var timer = null;
var started = false;
toggleCard = function (card) {
if (started) {
console.log('Timer already active');
window.clearTimeout(timer);
} else {
console.log('Timer active now');
started = true;
}
timer = setTimeout(function () {
console.log('Timer elapsed! ');
started = false;
}.bind(this), 2000);
};
【解决方案4】:
每次调用该函数时,您都会创建一个新的 Timer 变量,因此当您尝试清除超时时,Timer 变量不会引用您创建的实际超时。