🥇 函数防抖(debounce):

  • 概念: 延迟要执行的动作,若在延迟的这段时间内,再次触发了,则取消之前开启的动作,重新计时。
    举例: 电脑无操作1分钟之内如果没有操作会进入休眠,当第40秒时鼠标被移动一下,重新计时1分钟。
    实现: 定时器。
    * 应用: 搜索时等用户完整输入内容后再发送查询请求。
    1. input.addEventListener("keyup", (function (e) {
    2. var t = null;
    3. return function () {
    4. if (t) {
    5. clearTimeout(t)
    6. }
    7. t = setTimeout(function () {
    8. if (input.value.length) {
    9. console.log('1');
    10. }
    11. }, 300);
    12. }
    13. })())

🥇 函数节流(throttle):

  • 概念:设定一个特定的时间,让函数在特定的时间内只执行一次,不会频繁执行
    举例:fps游戏,鼠标按住不松手,子弹也不会连成一条线
    实现:定时器、标识
    * 实现:定时器、标识
    1. let isCanLog = true
    2. document.body.onscroll = function () {
    3. if(isCanLog){
    4. console.log(1)
    5. isCanLog = false
    6. setTimeout(function () {
    7. isCanLog = true
    8. },1000)
    9. }
    10. }