Javascript节流函数



一、什么是节流函数?

在前端开发中,onscroll、onresize、onchange、mousemove等事件的回调函数,总会被频繁的触发调用:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>节流函数</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="//lib.mzwu.com/jquery/jquery-1.12.4.min.js"></script>
</head>

<body>
    <input id="usn" />
    <script>
        $(document).ready(function(){
            let query = function(content){
                console.log("连接服务器查询-", content);
            }

            $("#usn").on("input propertychange", function(){
                query($(this).val());
            })
        });
    </script>
</body>
</html>



我们可以人为干预限制函数调用次数,限制在n秒中只执行一次,2n秒只执行2次,3n秒只执行3次,依此类推,这就是节流函数。

二、Javascript实现节流函数

1.时间差版本

<script>
    $(document).ready(function(){
        //节流函数改造器
        let throttle = function(fn, delay) {
            let previous = 0;
            return function() {
                let args = arguments;
                let now = new Date();
                //第一次不查询
                // if(previous == 0){
                //     previous = new Date();
                // }

                if(now - previous > delay) {                        
                    previous = now;
                    fn.apply(null, args);
                }
                // else{
                //     console.log("不查询-", arguments[0]);
                // }
            }
        }

        //直正要执行的函数,待改造成节流函数
        let query = function(content){
            console.log("连接服务器查询-", content);
        }

        //节流函数,3秒内只执行一次
        let throttle_query = throttle(query, 3000);

        $("#usn").on("input propertychange", function(){
            throttle_query($(this).val());
        })
    });
</script>



2.定时器版本

<script>
    $(document).ready(function(){
        //节流函数改造器
        let throttle = function(fn, delay) {
            let timer;
            return function() {
                let args = arguments;
                if(!timer){
                    timer = setTimeout(function(){
                        timer = null;
                        fn.apply(null,args);
                    },delay);
                }
                // else{
                //     console.log("不查询-", arguments[0]);
                // }
            }
        }

        //直正要执行的函数,等待改造成节流函数
        let query = function(content){
            console.log("连接服务器查询-", content);
        }

        //节流函数,3秒内只执行一次
        let throttle_query = throttle(query, 3000);

        $("#usn").on("input propertychange", function(){
            throttle_query($(this).val());
        })
    });
</script>



参考资料

[1].Javascript 实现函数节流(throttle):https://zhuanlan.zhihu.com/p/367106221
[2].节流函数:https://blog.csdn.net/bhq1711617151/article/details/115556353

评论: 0 | 引用: 0 | 查看次数: 655
发表评论
登录后再发表评论!