函数防抖debounce封装 + npm包 + jasmine单

2018-12-05  本文已影响194人  小宝薯
debounce

分析

  • 函数防抖需求原因
  • 实现原理
  • 封装,优化
  • 发布,成为npm包

正常情况下,一个input搜索框只要输入信息,就会调用ajax请求
公用代码:

<style>
    #i {
         width: 300px;
         height: 28px;
         margin-top:50px;
         margin-left:100px;
       }
</style>
<input type="text" id="i">
const i = document.getElementById('i');
const c = document.getElementById('content');

一、正常input搜索框触发请求

实时ajax请求
    i.oninput = () => {
      console.log(i.value);
      ajax(i.value);
    }
    function ajax(e) {
      console.log(e)
    }

二、函数防抖debounce

三、debounce思路

设定input输入后一定时间后才会触发事件,减少性能消耗

即延迟处理函数,如果设定的时间到来之前,又一次触发了事件,就清除上一次的定时器

具体代码

let count = 0;
    let timer;
    i.oninput = () => {
        if(timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            ajax();
            timer = null;
        }, 300);
    }
    function ajax() {
        console.log(`ajax${++count}`);
    }
debounce函数防抖

四、优化封装debounce

代码如下

let count = 0;
    const debounce = debounceWrapper(ajax, 300);
    i.oninput = () => {
        debounce();
    }

    function debounceWrapper(fn, debounceTime = 300 ) {
        let timer; 
         return function() {
            if(timer) {
            clearTimeout(timer);
            }
            timer = setTimeout(() => {
                fn();
                timer = null;
            }, debounceTime);
         }
    }
    function ajax() {
        console.log(`ajax${++count}`);
    }

五、jasmine 单元测试

npm install jasmine --save-dev // 安装jasmine dev环境下单元测试包

// package.json 修改test的文件目录
 "scripts": {
    "test": "node node_modules/jasmine/bin/jasmine test/test.js"
  },
 "main": "src/index.js", // 入口文件

// 跑单元测试
npm run test
var debounceTransfer = require('..')

describe('debounce test case', function () {
    var fn
    var debounce
    beforeEach(function () {
        fn = jasmine.createSpy('fn')
        debounce = debounceTransfer(fn, 500)
        jasmine.clock().install()
    })

    afterEach(function () {
        jasmine.clock().uninstall()
    })
    
    it('test case1', function () {
        debounce()
        jasmine.clock().tick(500)
        expect(fn).toHaveBeenCalledTimes(1)
    })

    it('test case2', function () {
        debounce()
        debounce()
        jasmine.clock().tick(500)
        expect(fn).toHaveBeenCalledTimes(1)
    })

})
单元测试跑通

下载

npm 下载
github下载
上一篇 下一篇

猜你喜欢

热点阅读