Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

为什么要用setTimeout代替setInterval? #26

Open
lovelmh13 opened this issue Feb 4, 2020 · 0 comments
Open

为什么要用setTimeout代替setInterval? #26

lovelmh13 opened this issue Feb 4, 2020 · 0 comments

Comments

@lovelmh13
Copy link
Owner

在用setInterval的时候,我们这么用:

var num = 0;
var max = 10;
var timer = undefined;

function fn () {
	num ++;
	if (num === max) {
		clearInterval(timer);
		alert('完成')
	}
}
timer = setInterval(fn, 1000);

但是有一个问题,就是可能我们的下一个定时器会在上一个定时器还没有结束前就启动,那么在清除定时器的时候,timer就会出问题。 所以我们应该规避这个问题。

可以用setTimeout来实现同样的功能来避免:

var num = 0;
var max = 10;

function fn () {
	num ++;
	if (num < max) {
		setTimeout(fn, 1000);
	} else {
		alert('完成');
	}
}

省去了清除计时器ID的问题,避免了上述问题。

所以通常用setTimeout代替setInterval

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant