• 节流和防抖


    节流 throttle

    节流(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数。

    函数节流主要有两种实现方法:时间戳和定时器。

     var throttle = function(func, delay) {
        var prev = Date.now();
        return function() {
            var context = this;
            var args = arguments;
            var now = Date.now();
            if (now - prev >= delay) {
                func.apply(context, args);
                prev = Date.now();
            }
        }
    }
    function handle() {
        console.log(Math.random());
    }
    window.addEventListener('scroll', throttle(handle, 1000));
     

    当高频事件触发时,第一次会立即执行(给scroll事件绑定函数与真正触发事件的间隔一般大于delay),而后再怎么频繁地触发事件,也都是每delay时间才执行一次。而当最后一次事件触发完毕后,事件也不会再被执行了

     
     var throttle = function(func, delay) {
        var timer = null;
        return function() {
            var context = this;
            var args = arguments;
            if (!timer) {
                timer = setTimeout(function() {
                    func.apply(context, args);
                    timer = null;
                }, delay);
            }
        }
    }
    function handle() {
        console.log(Math.random());
    }
    window.addEventListener('scroll', throttle(handle, 1000));
     

    防抖 debounce

    防抖(debounce):当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。

     
     
     
     
     
     
    function debounce(fn, wait) {
        var timeout = null;
        return function() {
            if(timeout !== null) 
                clearTimeout(timeout);
            timeout = setTimeout(fn, wait);
        }
    }
    // 处理函数
    function handle() {
        console.log(Math.random()); 
    }
    // 滚动事件
    window.addEventListener('scroll', debounce(handle, 1000));
  • 相关阅读:
    LaTeX不能识别eps文件?
    ubuntu 11.04系统清理(不断更新。。。)
    换Ubuntu邮件客户端Evolution为Thunderbird
    Byobu:打造多任务的Terminal
    Learning the Vi Editor, 6th Edition学习笔记(1)
    Ubuntu:让桌面显示回收站
    3rd Party Repository for Dropbox
    ubuntu 显示隐藏文件
    Ubuntu下的一款Dock工具AWN
    i686和x86_64的区别
  • 原文地址:https://www.cnblogs.com/wangsai-666/p/11977592.html
Copyright © 2020-2023  润新知