debounce

function debounce( func, wait, immediate ) {
        var timeout, args, context, timestamp, result;

        var later = function() {
            var last = +new Date() - timestamp;

            if ( last < wait && last >= 0 ) {
                timeout = setTimeout( later, wait - last );
            } else {
                timeout = null;
                if ( !immediate ) {
                    result = func.apply( context, args );
                    if ( !timeout ){
                        context = args = null;
                    }
                }
            }
        };

        return function() {
            context = this;
            args = arguments;
            timestamp = +new Date();//++每次调用此函数,都会刷新timestamp,所以才出现later中的if判断1,可类比线段
            var callNow = immediate && !timeout;
            if (!timeout){
                timeout = setTimeout( later, wait );
            }
            if (callNow) {
                result = func.apply( context, args );
                context = args = null;
            }

            return result;
        };
    };

你可能感兴趣的:(debounce)