我在Javascript中遇到间隔问题。这个例子说明了一切
var foo = {
counter: function() {
// static variable
if( typeof this.totalNumbers === 'undefined' )
this.totalNumbers = 5;
if( typeof this.counterInterval === 'undefined' ) {
document.body.innerHTML +=
'<p>this is being executed twice and then ' +
'js decides its not undefined anymore ' +
'after setting 2 intervals</p>'
;
this.counterInterval = setInterval(this.counter, 1000);
return;
}
// now works perfectly but with two intervals...
this.totalNumbers -= 1;
document.body.innerHTML += '<p>' + this.totalNumbers + '</p>';
if( this.totalNumbers === 0 ) {
delete this.totalNumbers;
clearInterval( this.counterInterval );
document.body.innerHTML +=
'now the last interval was deleted but the function' +
' keeps running';
}
},
};
foo.counter();
答案 0 :(得分:4)
您需要绑定计数器功能,然后再将其传递给setInterval
this.counterInterval = setInterval(this.counter.bind(this), 1000);
否则this
在第一次通话和第二次通话
var foo = {
counter: function() {
// static variable
if( typeof this.totalNumbers === 'undefined' )
this.totalNumbers = 5;
if( typeof this.counterInterval === 'undefined' ) {
document.body.innerHTML +=
'<p>this is being executed twice and then ' +
'js decides its not undefined anymore ' +
'after setting 2 intervals</p>'
;
this.counterInterval = setInterval(this.counter.bind(this), 1000);
return;
}
// now works perfectly but with two intervals...
this.totalNumbers -= 1;
document.body.innerHTML += '<p>' + this.totalNumbers + '</p>';
if( this.totalNumbers === 0 ) {
delete this.totalNumbers;
clearInterval( this.counterInterval );
document.body.innerHTML +=
'now the last interval was deleted but the function' +
' keeps running';
}
},
};
foo.counter();