gpt4 book ai didi

javascript - 为什么 Javascript 在设置变量时速度很慢?

转载 作者:行者123 更新时间:2023-11-28 15:11:55 29 4
gpt4 key购买 nike

我在 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();

最佳答案

您需要先绑定(bind)计数器函数,然后再将其传递给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();

关于javascript - 为什么 Javascript 在设置变量时速度很慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36047644/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com