- 函数节流
var oDiv = document.getElementById('div1')
function throttle(fn,delay){
var startTime = 0
return function(){
var nowTime = Date.now()
if(nowTime -startTime > delay){
fn.call(this)//在这得调用一些串进来的的fn()
startTime = nowTime
}
}
}
document.onmousemove = throttle(function(){
// console.log(111)
console.log(Date.now())
console.log(this)
},1000)
// 当不改变指针时这个this指向的是window
// 改变指针后指向的是document
- 函数防抖
<script>
// 函数去抖动,只对最后一次生效
var oBtn =document.getElementById('btn')
function debounce(fn,delay){
var timer = null
return function(){
clearTimeout(timer)
timer = setTimeout(function(){
fn.apply(this)
},delay)
}
}
oBtn.onclick = debounce(function(){
console.log(Date.now())
},300)
</script>