zoukankan      html  css  js  c++  java
  • javascript函数节流(throttle)与函数去抖(debounce)

    throttle 等时间 间隔执行函数。

    debounce 时间间隔 t 内若再次触发事件,则重新计时,直到停止时间大于或等于 t 才执行函数。

    1、throttle函数的简单实现

    function throttle(fn, threshhold, scope) { 
        threshhold || (threshhold = 250); 
        var last, timer; 
        return function () {
            var context = scope || this; 
            var now = +new Date(), 
                args = arguments; 
            if (last && now - last + threshhold < 0) { 
                // hold on to it 
                clearTimeout(deferTimer); 
                timer = setTimeout(function () { 
                    last = now; 
                    fn.apply(context, args); 
                }, threshhold); 
            } else { 
                last = now; 
                fn.apply(context, args); 
            } 
        };
    }
    
    //调用方法
    $('body').on('mousemove', throttle(function (event) {
        console.log('tick');
    }, 1000));

    2、debounce函数的简单实现

    function debounce(fn, delay) { 
        var timer = null; 
        return function () { 
            var context = this,
            args = arguments; 
            clearTimeout(timer); 
            timer = setTimeout(function () { 
                fn.apply(context, args); 
            }, delay); 
        };
    }
    
    //调用方法
    $('input.username').keypress(debounce(function (event) {
    // do the Ajax request
    }, 250));

    转自:http://www.cnblogs.com/fsjohnhuang/p/4147810.html

  • 相关阅读:
    常用模块
    python里面的奇技淫巧
    day_06、面向对象(二)
    day_06、面向对象
    day_06、递归、二分查找
    day_05、内置函数、匿名函数
    day_05、迭代器、生成器
    day_04、函数
    php调用webservice接口
    php在命令行输出进度条
  • 原文地址:https://www.cnblogs.com/ilovexiaoming/p/6826629.html
Copyright © 2011-2022 走看看