js超时调用和间歇调用
超时调用
//不建议传递字符串
setTimeout(“alert(‘hello,world’)”,1000);
//推荐使用方式
setTimeout(function(){
alert(‘hello,world’);
},1000);
clearTimeout()来取消
间歇调用
setInterval()方法
setInterval(function(){
alert(‘hello,world’);
},1000);
clearInterval方法取消
用超时调用模拟间歇调用实例
<html>
<head>
<script>
var num=1
var max=0
function addnum(){
alert('~~~~'+num); //你 所 要做 的 事
if(num>max){
setTimeout(addnum,5000)
}else{
}
num++
}
setTimeout(addnum,500)
</script></head>
<body></body>
</html>
//类似于监听事件,或者持续不间断刷新请求时会用到,故意写num>max,如果想让事件在一定时间停止,可以,num