zoukankan      html  css  js  c++  java
  • 什么是函数节流?

    什么是函数节流?

    介绍前,先说下背景。在前端开发中,有时会为页面绑定resize事件,或者为一个页面元素绑定拖拽事件(其核心就是绑定mousemove),这种事件有一个特点,就是用户不必特地捣乱,他在一个正常的操作中,都有可能在一个短的时间内触发非常多次事件绑定程序。而大家知道,DOM操作时很消耗性能的,这个时候,如果你为这些事件绑定一些操作DOM节点的操作的话,那就会引发大量的计算,在用户看来,页面可能就一时间没有响应,这个页面一下子变卡了变慢了。甚至在IE下,如果你绑定的resize事件进行较多DOM操作,其高频率可能直接就使得浏览器崩溃。

    函数节流的原理

    函数节流的原理挺简单的,估计大家都想到了,那就是定时器。当我触发一个时间时,先setTimout让这个事件延迟一会再执行,如果在这个时间间隔内又触发了事件,那我们就clear掉原来的定时器,再setTimeout一个新的定时器延迟一会执行,就这样。

    var main = {
    
        changeScreen: {
            init: function() {
                var _this = this;
                _this.obtainScreen();
                _this.resizeScreen();
            },
    
            obtainScreen: function() {
                var screenWidth,
                    ua = navigator.userAgent.toLocaleLowerCase(),
                    v = $.browser.version,
                    $resizeScreen = $( "#resizeScreen" );
    
                screenWidth = window.innerWidth ? window.innerWidth :
                    document.documentElement.clientWidth;
    
                if ( ua.indexOf( "msie" ) > -1 && +v < 10 ) { 
                    if( screenWidth >= 1540 ) {
                        $resizeScreen.addClass( "w1240" );
                    } else {
                        $resizeScreen.removeClass( "w1240" );
                    }
                }
            },
    
            //函数节流的原理挺简单的,估计大家都想到了,那就是定时器
            throttle: function( fn, delay ) {
                var timer = null;
                return function() {
                    var context = this, args = arguments;
                    clearTimeout( timer );
                    timer = setTimeout(function() {
                        fn.apply( context, args );
                    }, delay );
                };
            },
    
            resizeScreen: function() {
                var _this = giftCommon.changeScreen;
    
                window.onresize = _this.throttle( _this.obtainScreen, 100 );
            }
        }
    
    };
  • 相关阅读:
    EJB
    Token
    FreeMarker
    solr
    maven学习四:maven集成jetty插件发布web项目 标签: maven
    代码生成器
    springIOplatform
    数据连接池
    freeMark模板引擎
    张萌作品集
  • 原文地址:https://www.cnblogs.com/frontendBY/p/4876711.html
Copyright © 2011-2022 走看看