2016-03-16 80 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

相關問題