Home > Web Front-end > JS Tutorial > The meaning of function throttling and anti-shake

The meaning of function throttling and anti-shake

一个新手
Release: 2017-09-22 09:39:53
Original
1925 people have browsed it


function debounce(fn, delay, immediate){
    var timeout,
        args,
        context,
        timestamp,
        result;    
        var later = function(){
        var last = Date.now() - timestamp;       
        if(last < delay && last >= 0){
            timeout = setTimeout(later, delay - last);
        }else{
            timeout = null;            
            if(!immediate){
                result = fn.apply(context, args);                
                if(!timeout){
                    context = args = null;
                }
            }
        }
    };    return function(){
        context = this;
        args = arguments;
        timestamp = Date.now();
        console.log(timestamp);        
        var callNow = immediate && !timeout;        
        if(!timeout){
            timeout = setTimeout(later, delay);
        }        if(callNow){
            result = fn.apply(context, args);
            context = args = null;
        }        return result
    }
};function throttle(method , duration ,delay ){
    var timer = null, 
        // 记录下开始执行函数的时间
        begin = new Date();    
        return function(){
        var context = this, 
            args = arguments, 
            // 记录下当前时间
            current = new Date();        // 函数节流里的思路
        clearTimeout(timer);        // 记录下的两个时间相减再与duration进行比较
        if(current-begin >= duration){
             method.apply(context , args);
             begin = current;
        }else{  
            timer = setTimeout(function(){
                method.apply(context , args);
            } , delay);
        }
    }
}
window.onresize = throttle(function(){console.log(&#39;resize&#39;)},1000,500)
Copy after login

The above is the detailed content of The meaning of function throttling and anti-shake. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template