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

时间:2016-03-16 21:51:07

标签: javascript setinterval

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

1 个答案:

答案 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();