JavaScript 函数节流

其实最早看设计模式是单纯的了解js语言本身;所以看了理解了之后还是容易忘记;可能之后实际的工作需要才能记住吧;

看下面:<!DOCTYPE html>

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    
</body>

</html>
<script>
    window.onresize=function(){
        con();
    };

    function con(){
        console.log("aaaaa")
    }
</script>

上述情况,浏览器大概每秒会检查到10次左右的窗口变化;显然对性能不利;

下面看一个节流函数做的处理:

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    
</body>

</html>
<script>

window.onresize=function(){ throttle(con,300); }; function con(){ console.log("aaaaa") }
//节流器函数; function throttle() {     var first_param = arguments[0], methods,time_param;     if (typeof first_param === 'boolean') {         methods = arguments[1];     methods.throttleTimeId && clearTimeout(methods.throttleTimeId);     } else {          methods = first_param;          arguments.callee(true, methods); //arguments.callee指向函数的引用; //无闭包,立即销毁内存;     time_param = arguments[1]||500//默认500毫秒; //函数的argument指向的是 实参;     // window.throttle(true, methods); //arguments.callee指向函数的引用;     //为函数绑定计时器,延迟执行     methods.throttleTimeId = setTimeout(function () {       methods();     },time_param)   } } </script>

通过把要执行的函数传入到节流函数中,达到效果;

当用户重复快速拖动窗口的时候,在设定的时间内 time_param;防抖函数检测有true时,马上就清楚了函数的执行,除非用户在规定时间不再操作;

这个用在ajax重复提交按钮上面也是一样的;

简单假设:

<input  value="查询" id="btns">

$("#btns").on("click",function(){

 throttle(query,300);

})

function query(){

  $.ajax({

    url:"api/user",

    method:"post",

         data:{

      "name":"liuliu"

    },

         success:function(res){

      console.log(res)

    }

  })

}

原文地址:https://www.cnblogs.com/liuliu-hai/p/9025199.html