定时器
JavaScript提供定时执行代码的功能,叫做定时器(timer),主要由setTimeout()和setInterval()这两个函数来完成。两者都是全局属性
一、setTimeout()
setTimeout函数用来指定某个函数或某段代码,在多少毫秒之后执行。它返回一个整数,表示定时器的编号,以后可以用来取消这个定时器。
语法:var tinmerId = setTimeout(func|code,delay)
第一个参数是将要执行的函数或者一段代码,第二个参数是推迟执行的毫秒数。
var timer = setTimeout(function(){console.log('hello')},1000)//返回一个编号(19),一秒后输出“hello”
setTimeout(function(){console.log('hello')},1000)//返回一个编号(20),一秒后输出“hello”
var timer = setTimeout(function(){console.log('hello')},10000)//返回一个编号(21),10秒后输出“hello”
clearTimeout(timer)//可以在还没有输出时,停止执行
clearTimeout(22)//可以直接清除编号
立即返回的是延迟的编号,下次可以直接调用编号
setInterval()
与setTimeout用法完全一致,setInterval指定某个任务每间隔一段时间执行一次,是无限次的定时执行。
var timer = setInterval(function(){
console.log(new Date())
},1000)
//每隔一秒,输出当前时间
clearInterval(timer)//清除
运行机制
将指定代码移出本次执行 ,等到下一轮Event Loop时,再检查 是否到了指定时间。如果到了,就政治性对应的代码;如果没到,就等下一轮Event Loop时重新判断 。
浏览器一般有最小时间间隔(4-10毫秒),设置的时间是尽可能的贴近,而不是严格的执行时间。
异步和回调
函数节流
设置一个定时器,先判断是否有定时器,没有的话就设置一个,有的话就清除上一次的再重新设置一个定时器
var timer
function hiFrequency() {
if(timer) {
clearTimerout(timer)
} //第一次timer没有值,不执行;如果不足1秒又执行了一次,就清除timer的值
timer = setTimerout(function(){
console.log('hello world')
},1000) //一秒后输出,不足1秒再次执行就会先运行上面代码清除,只输出最后一次超过1秒没有继续执行的代码
hiFrequency()
hiFrequency()
hiFrequency()
}
优化上面代码:
function throttle(fn,delay){
var timer = null
return function(){ //返回一个函数
clearTimeout(timer)
timer = setTimeout(function(){
fn(arguments)
},delay)
}
}
function fn(){
console.log('hello')
}
var fn2 = throttle(fn,1000)//执行的是返回的函数
fn2()
fn2()
fn2()