高频执行事件延迟执行

对于高频率执行执行事件(如 scroll, resize 等),每动一像素就执行一次回调,如果回调非常复杂,对于性能损耗是比较严重的,有时候甚至会造成浏览器假死,因此有必要对事件回调进行延迟执行,看underscore 是如何处理的

_.debounce = function (func, wait, immediate){
    var timeout, context, args, timestamp,
        later = function (){
            var last = new Date().now() - timestamp;
            if(last < wait && last >=0){
                timeout = setTimeout(func, wait-last);
            }else{
                timeout = null;
                if(!immediate){
                    func.apply(context, args);
                    if (!timeout) context = args = null;
                }
            }
        }

    return function (){
        args = arguments;
        context = this;
        timestamp = new Date.now();

        var callnow = immediate && !timeout;
        if(!timeout) timeout = setTimeout(later, wait);
        if(callnow){
            func.apply(context, args);
            context = args = null;
        }
    }

}

使用:

addEventListener('scroll', _.debounce(function (){

  // scroll handler code goes here

}, 300));

 

当滚动页面时,回调函数每300ms才会执行一次.

posted @ 2015-10-22 14:56  胖子2  阅读(249)  评论(0编辑  收藏  举报