#43 函数防抖 debounce
-
0
@陈小俊 你好,setTimeout的第一个参数为什么外面要多一层匿名函数呢?我不加这个匿名函数也能通过测试用例
-
0
@ScriptOJ
这个该怎么和点击事件联合使用啊,大神
-
0
@陈小俊 在 #43 函数防抖 debounce 中说:
const debounce = (fn, duration) => {
let timer = null;
return () => {
clearTimeout(timer)
timer = setTimeout(() => {
fn()
}, duration)
}
}duration有作用吗?
-
0
var debounce = (n) => { var old return e => { var gap =+new Date - old if(gap /1000 <= n){ console.log('正忙...') return } old = +new Date() console.log('test') } }
-
0
let debounce = (fn, duration) => {
var curTime=0 return function akb() { if ( (new Date().getTime() - curTime )> duration) { curTime = new Date().getTime() fn(); } }
}
这样写在浏览器测试是可以的,可是不通过
-
0
@okaykop 一旦到了duration, 就一定会执行请求,但这时,可能仍在高频请求
-
0
@okaykop 这个应该就是实现了前面贴子提到的throttle,而不是debounce
-
0
之前把函数防抖和函数节流弄反了,现在搞懂了。
-
0
按正常思路就可以了 ,没有那么麻烦,注意题目要求返回一个函数,不就是闭包嘛
const debounce = (fn, duration) => { let timer = null return () => { clearTimeout(timer) timer = setTimeout(fn,duration) } }
-
0
-
0
函数节流debounce
多用于搜索框,当其被疯狂、高频地点击,这个函数最后只会被执行一次。
实现思路: 每次点击都先清除之前的timer,然后重新设定定时器,以确保fn只执行一次
const debounce = (fn, duration) => { let timer = null let fns = () => { clearTimeout(timer) timer = setTimeout(fn,duration) } return fns }
函数节流throttle
多用于具有倒计时功能的按钮,当点击发送按钮后,开始进行倒计时,这期间无法发送,当倒计时结束后,可再次发送
实现思路: 在发送后开始倒计时,倒计时结束后清除timer,这期间所有请求全部 return false
const throttle= (fn, duration) => { let timer = null; let fns = () => { if (timer) { return false; } else { timer = setTimeout(() => { timer = null; }, duration); return fn(); } }; return fns; };