JavaScript面试题-函数节流?防抖?

mac2025-11-27  11

函数节流

一个函数执行一次后,只有大于设定的执行周期后才会执行第二次

function throttle(fun, delay) { let startTime = 0 // this 为 window console.log(this) // 将函数作为返回值返回 return function () { let nowTime = Date.now() // 当时间间隔大于 设定的时间间隔 时调用函数 if (nowTime -startTime > delay) { // this 为 document console.log(this) fun() // 修改this 指向将其改为 document // fun.call(this) startTime = nowTime } } } document.onmousemove = throttle(function () { console.log(Date.now()) // 未修改 this 指向时,this 为 window console.log(this) }, 3000)

防抖

一个需要频繁触发的函数,在规定时间内只让最后一次生效

let txt = document.getElementById('txt') function debounce(fn, delay) { let timer = null return function () { // 先清除定时器 clearTimeout(timer) // 创建定时器 timer = setTimeout(function() { // 修改 this 指向 fn.apply(this) console.log(this) }.bind(this), delay) } } txt.onkeyup = debounce(function () { console.log('防抖') console.log(this) }, 1000)
最新回复(0)