• 注册
当前位置:1313e > 默认分类 >正文

节流阀,防抖动函数

    function debounce(fn,delay,immediate=false){//防抖动var timerreturn function () {var context = thisvar arg = argumentsif(timer && !immediate){clearTimeout(timer)}timer = setTimeout(() => {fn(arg)}, delay);}}//初始化 debounce(() => console.log(new Date().getTime()), 2000) 改函数已经执行了// 相当于监听click执行的事件是debounce内部return出来的 匿名 functiondocument.addEventListener('click', debounce(() => console.log(new Date().getTime()), 2000), false)function throttle(fn, threshhold) { //节流阀// 记录上次执行的时间var last// 定时器var timer// 默认间隔为 250msthreshhold || (threshhold = 2500)// 返回的函数,每过 threshhold 毫秒就执行一次 fn 函数return function () {var context = thisvar args = argumentsvar now = new Date().getTime()// 如果距离上次执行 fn 函数的时间小于 threshhold,那么就放弃// 执行 fn,并重新计时if (last && now < (last + threshhold)) {clearTimeout(timer)// 保证在当前时间区间结束后,再执行一次 fntimer = setTimeout(function () {last = nowfn.apply(context, args)}, threshhold)// 在时间区间的最开始和到达指定间隔的时候执行一次 fn} else {last = nowclearTimeout(timer)fn.apply(context, args)}}}// function fn(){//     console.log('333')// }// document.addEventListener('click', throttle(fn,2500), false)//类似的其实还有这种函数,和vue的once api 原理是一样的function once (fn){let called = falsereturn function () {if (!called) {called = truefn.apply(this, arguments)}}}//以上三个函数,其实都是闭包的应用,//现在,如果别人在问完你闭包特点等问题之后,再问你实际的应用场景,那么你可以列举出以上三个函数。

 

转载于:https://www.cnblogs.com/hjj2ldq/p/10437055.html

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 162202241@qq.com 举报,一经查实,本站将立刻删除。

最新评论

欢迎您发表评论:

请登录之后再进行评论

登录