以前,贴吧骗赞有个说法,快速点击两次可以赞两下哦,这个情况倒是可以发生的,就是将点赞信息提交了多次。就算后端帮助判断了不能点赞多次,将错误信息返回前台,频繁提示“不能多次点赞”看起来也是很Low。我们可以根据需求来使用下面几种方式让效果、性能都能完美实现。
防抖的原理是在规定触发时间内,多次点击,都会重新刷新触发时间,直到触发时间完成回调才会触发。防抖的运用场景大多在搜索关联词匹配、window窗口的变化已经滚动条的滚动。
节流的原理是在规定时间内不管点击多少次都只会执行一次。而像我们提交信息的话,需要的是当后台返回信息后,我们做自己的逻辑判断。节流的运用场景在瀑布流更新列表信息、当然短时间内不能重复提交、点击事件也可以拿来使用。
防抖的核心实现代码如下:
1 //防抖 2 function debounce(fun, delay = 200) { 3 return function (args) { 4 //获取函数的作用域和变量 5 let that = this 6 let _args = args 7 //每次事件被触发,都会清除当前的timeer,然后重写设置超时调用 8 clearTimeout(fun.id) 9 fun.id = setTimeout(function () {10 fun.call(that, _args)11 }, delay)12 }13 }
节流的核心实现代码如下:
1 //节流 2 function throttle(fun, delay = 1000) { 3 let last, deferTimer; 4 return function (args) { 5 let that = this; 6 let _args = arguments; 7 8 let now = +new Date(); 9 if (last && now < last + delay) {10 clearTimeout(deferTimer);11 deferTimer = setTimeout(function () {12 last = now;13 fun.apply(that, _args);14 }, delay)15 } else {16 last = now;17 fun.apply(that, _args);18 }19 }20 }
而点击期间不能再次点击,我们可以设置一个全局变量,用户点击后变量切换状态,该状态不能再次点击操作。