js定时器使用:
场景:发送验证码时需要等段一段时间后才能重新发送,需要用到定时器计时。
setTimeout:
setTimeout(function,timeout);
例如:
var timerId = setTimeout(method,1000);
fuction method(){
//do something
}
效果:
延时1秒后执行,只执行一次。
可用递归调用,达到每隔一个时间段执行。
var timerId = setTimeout(method,1000);
fuction method(){
//do something
method();
clearTimeout(timerId);
timerId = setTimeout(method,1000);
}
若想达到某个条件自动停止:
var timerId = setTimeout(method,1000);
fuction method(){
if(true){
clearTimeout(timerId);
return;
}
//do something
method();
clearTimeout(timerId);
timerId = setTimeout(method,1000);
}
setInterval:
setInterval(function,timeout);
例如:
var timerId = setInterval(method,1000);
fuction method(){
//do something
}
效果:
每间隔1秒执行一次。
区别:
非前端人员,暂不深究。