为什么 Javascript 设置变量时很慢?

Why is Javascript being slow when setting variables?

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

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