JavaScript 函數節流

來源:互聯網
上載者:User

標籤:nbsp   post   ati   method   eof   執行   視窗   callee   ble   

其實最早看設計模式是單純的瞭解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)

    }

  })

}

 

JavaScript 函數節流

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.