函数节流与防抖


1.节流

节流是防止监听函数多次执行造成的性能浪费。例如监听鼠标移动可以隔一段时间监听一次

function throttle(fn, wait) {
    var lastTime = null
    return function () {
        if (lastTime == null || Date.now() - lastTime > wait) {
            fn.apply(this, arguments)
            lastTime = Date.now()
        }
    }
}
const vm = new Vue({
    el: '#app',
    data: {},
    methods: {
        move: throttle(function (e) {
            console.log(e.clientX, e.clientY);
        }, 500)
    }
})

2. 防抖

防抖是为了限制用户的操作频率来节省性能。例如检测搜索框键盘抬起

function debounce(fn, wait) {
    var timeOutId = null
    return function () {
        if (timeOutId) {
            clearTimeout(timeOutId)
        }
        timeOutId = setTimeout(() => {
            fn.apply(this, arguments)
        }, wait);
    }
}
const vm = new Vue({
    el: '#app',
    data: {},
    methods: {
        search: debounce(
            function (e) {
                console.log(e);
            }, 500
        )
    }
})