Underscore.js 函数节流简单测试

函数节流在日常的DOM界面数据交互中有比较大的作用,可以减少服务器的请求,同时减少客户端的内存影响

Underscore.js  本省就包含了函数节流的处理函数 

_.throttle 和 _.debounce 

简单的测试使用如下:

需要使用的类库为jquery  、Underscore 

测试的方法为:mousemove 事件

测试页面代码如下:

<!DOCTYPE html >
<html>
<head>
    <script src="jquery-1.11.1.min.js" type="text/javascript"></script>
    <script src="underscore-min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#infoapp').on('mousemove', alertinfo);  不使用节流方法

         //   $('#infoapp').on('mousemove', _.throttle(alertinfo, 5000));    使用节流方法  throttle

         //   $('#infoapp').on('mousemove', _.debounce(alertinfo, 1000, false));    使用节流方法debounce
        }
        )
       //  进行回调的事件处理函数
        function alertinfo() {

            var data = new Date();
            console.log(data);
        }
    </script>
</head>
<body>
    <div id="infoapp" style="background-color: Red;  200px; height: 200px;   margin:0 auto;">
    </div>
</body>
</html>

测试的结果如下:

结论:

 总的来说对于我们在密集数据请求的ajax 交互中使用函数节流的方式有很大的帮助,减少了很多的没有必要的数据请求。

原文地址:https://www.cnblogs.com/rongfengliang/p/4555102.html