2016-03-16 81 views
0

我在使用Javascript的间隔时遇到问题。这个例子说明了一切为什么Javascript在设置变量时速度很慢?

var foo = { 
 

 
\t counter: function() { 
 
\t \t // static variable 
 
\t \t if(typeof this.totalNumbers === 'undefined') 
 
\t \t \t this.totalNumbers = 5; 
 

 
\t \t if(typeof this.counterInterval === 'undefined') { 
 
\t \t \t document.body.innerHTML += 
 
\t \t \t \t '<p>this is being executed twice and then ' + 
 
\t \t \t \t 'js decides its not undefined anymore ' + 
 
\t \t \t \t 'after setting 2 intervals</p>' 
 
\t \t \t ; 
 
\t \t \t this.counterInterval = setInterval(this.counter, 1000); 
 
\t \t \t return; 
 
\t \t } 
 
\t \t // now works perfectly but with two intervals... 
 
\t \t this.totalNumbers -= 1; 
 
\t \t document.body.innerHTML += '<p>' + this.totalNumbers + '</p>'; 
 

 
\t \t if(this.totalNumbers === 0) { 
 
\t \t \t delete this.totalNumbers; 
 
\t \t \t clearInterval(this.counterInterval); 
 
\t \t \t document.body.innerHTML += 
 
\t \t \t \t \t 'now the last interval was deleted but the function' + 
 
\t \t \t \t \t ' keeps running'; 
 
\t \t } 
 
\t }, 
 
}; 
 
foo.counter();

回答

4

你需要之前绑定计数器功能将它传递给setInterval

this.counterInterval = setInterval(this.counter.bind(this), 1000); 

否则this是第一个电话和第二个电话之间的不同

var foo = { 
 

 
\t counter: function() { 
 
\t \t // static variable 
 
\t \t if(typeof this.totalNumbers === 'undefined') 
 
\t \t \t this.totalNumbers = 5; 
 

 
\t \t if(typeof this.counterInterval === 'undefined') { 
 
\t \t \t document.body.innerHTML += 
 
\t \t \t \t '<p>this is being executed twice and then ' + 
 
\t \t \t \t 'js decides its not undefined anymore ' + 
 
\t \t \t \t 'after setting 2 intervals</p>' 
 
\t \t \t ; 
 
\t \t \t this.counterInterval = setInterval(this.counter.bind(this), 1000); 
 
\t \t \t return; 
 
\t \t } 
 
\t \t // now works perfectly but with two intervals... 
 
\t \t this.totalNumbers -= 1; 
 
\t \t document.body.innerHTML += '<p>' + this.totalNumbers + '</p>'; 
 

 
\t \t if(this.totalNumbers === 0) { 
 
\t \t \t delete this.totalNumbers; 
 
\t \t \t clearInterval(this.counterInterval); 
 
\t \t \t document.body.innerHTML += 
 
\t \t \t \t \t 'now the last interval was deleted but the function' + 
 
\t \t \t \t \t ' keeps running'; 
 
\t \t } 
 
\t }, 
 
}; 
 
foo.counter();

+0

因此,这2小时的损失不是因为语言,而是因为我? :( – Zerquix18

相关问题