結構 行為 樣式 Js函式節流

2022-03-07 02:31:12 字數 2032 閱讀 1066

最近乙個面試官問了我乙個函式節流的問題,大概是:js 方法傳入兩個引數:乙個時間值、乙個函式,返回乙個函式。在這個時間間隔內,無論使用者怎麼觸發這個函式,只執行一次這個函式,直到這個時間走完才可以執行第二次這個函式。然後感覺自己工作中遇到過這個問題,但是不知道這種形式就是函式節流。下面我來說下這個js的高階問題,思路:函式節流就是防止使用者高頻呼叫某個事件而做的js層面的處理方法。主要就是在一定時間內讓使用者的操作只執行一次指定方法。

**實現(html):

doctype html

>

<

html

>

<

head

>

head

>

<

body

>

<

button

id="clickme"

value

="">點我,我不理你

button

>

body

>

<

script

src="test.js"

>

script

>

html

>

**實現(js):

function

st(num , fun),num);

return

fun;

}if(st.prototype.isopen == "ok")

}document.getelementbyid("clickme").addeventlistener('click',function

())

if(typeof myfun === "function")

myfun();

});

當然啦,這個只是本人在沒有參照的情況下自己的實現,其實社群中早就有人提出了這個最佳實踐(可能需要fq) 

下面這個就是社群中的最佳實踐:

var movers          = document.queryselectorall('.mover'),

lastscrolly = 0,

ticking = false;/*

* * set everthing up and position all the dom elements

* - normally done with the css but, hey, there's heaps

* of them so we're doing it here! */

(function

init()

})();/**

* callback for our scroll event - just

* keeps track of the last scroll value */

function

onscroll() /**

* calls raf if it's not already

* been done already */

function

requesttick() }/*

* * our animation callback */

function

update()

//second loop is going to go through

//the movers and add the left class

//to the elements' classlist

for(var m = 0; m < movers.length; m++)

else

}//allow further rafs to be called

ticking = false;}

//only listen for scroll events

window.addeventlistener('scroll', onscroll, false);

js函式節流(Throttle)

在瀏覽器 dom 事件裡面,有一些事件會隨著使用者的操作不間斷觸發。比如 重新調整瀏覽器視窗大小 resize 瀏覽器頁面滾動 scroll 滑鼠移動 mousemove 也就是說使用者在觸發這些瀏覽器操作的時候,如果指令碼裡面繫結了對應的事件處理方法,這個方法就不停的觸發。而當事件處理比較複雜的時...

js原生函式節流

函式節流就是一定時間內只觸發一次函式。原理是通過判斷是否到達一定時間來觸發函式。時間戳方案 function throttle fn,wait function handle window.addeventlistener mousemove throttle handle,1000 定時器方案 f...

JS總結 (一)函式節流

本篇思考三個問題 什麼是函式節流?為什麼要使用函式節流?如何實現?一 基本思想 某些 不可以在沒有間斷的情況連續重複執行。二 使用原因 dom操作比起非dom互動,需要更多的記憶體和cpu時間,連續嘗試過多的dom操作可能會導致瀏覽器掛起,甚至崩潰。三 實現方式 使用定時器對函式進行節流,即第一次呼...