我正在尝试在使用“ new”运算符创建的js对象中使用“ setInterval”和“ clearInterval”函数。
的HTML:
<button onclick="testList.push(new Test());">run</button>
js:
Test = function(){
this.y = 0;
this.dy = 10;
that = this;
this.interval = setInterval(function(){
that.y += that.dy;
if (that.y>300){
console.log(that.y); //prints y in console
clearInterval(that.interval);
}
}, 10);
}
当我单击“运行”按钮后,这将按我的预期工作。但是,当我多次单击“运行”按钮之前没有清除之前的间隔时(快速多次单击按钮),则间隔不会清除并且y无限增大。我在这里犯了什么错误?
先感谢您...
您正在创建一个全局变量that
,该全局变量将覆盖以前的Test
实例引用:
that = this;
var
声明变量时应使用关键字:
var that = this;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句