[英]Why setInterval not stopped by clearInterval
var progressbar = {
progress : null,
html : function() {
var loadingHtml = '<div id="loader-wrapper" class="catalog-loadmore">';
loadingHtml += '<div class="progress"><div id="catalog-bar" class="progress-bar progress-bar-striped active" style="width: 10%"></div></div>';
loadingHtml += '<div class=""><span id="progress-valuenow"></span>%</div>';
loadingHtml += '</div>';
return loadingHtml
},
start : function() {
var width = 10;
this.progress = setInterval(function() {
$('#catalog-bar').css('width', width + '%');
$('#progress-valuenow').text(width);
if(width < 98){
width += 1;
}else{
this.stop(); // this is not working
clearInterval(this.progress); // this is also not working
console.log('else')
}
}, 100);
},
stop : function() {
clearInterval(this.progress);
},
destroy : function() {
clearInterval(this.progress);
$('#loader-wrapper').remove();
}
}
在上面的代码中,为什么执行以下语句else条件不起作用console.log('else')
正在打印,但clearInterval()无法工作。 我从外面打电话给progressbar.destroy(),它正在工作。
this.stop(); // this is not working
clearInterval(this.progress); // this is also not working
谁能告诉我我做错了什么。
您已经将匿名函数传递给setInterval
,匿名函数this
上下文设置为window
,因此您的目标是window.progress
。
您有两种方法可以解决问题:
存储this
在像一些变量var _this = this; setInterval(function() { ... clearInterval(_this.progress) } ...)
var _this = this; setInterval(function() { ... clearInterval(_this.progress) } ...)
使用Function.prototype.bind()
设置您的匿名函数的上下文,如setInterval(function() { ... clearInterval(this.progress) }.bind(this) ...)
或为ES6设置transpiler并使用Arrow function
将this
自动绑定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.