utils:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
// 防抖 export const debounce = (func, wait = 3000, immediate = true ) => { let timeout = null ; return function () { let context = this ; let args = arguments; if (timeout) clearTimeout(timeout); if (immediate) { var callNow = !timeout; //點擊第一次為true 時間內點擊第二次為false 時間結束則重復第一次 timeout = setTimeout(() => { timeout = null ; }, wait); //定時器ID if (callNow) func.apply(context, args); } else { timeout = setTimeout( function () { func.apply(context, args); }, wait); } }; }; // 時間戳方案 export const throttleTime = (fn, wait = 2000) => { var pre = Date.now(); return function () { var context = this ; var args = arguments; var now = Date.now(); if (now - pre >= wait) { fn.apply(context, args); pre = Date.now(); } }; }; // 定時器方案 export const throttleSetTimeout = (fn, wait = 3000) => { var timer = null ; return function () { var context = this ; var args = arguments; if (!timer) { timer = setTimeout( function () { fn.apply(context, args); timer = null ; }, wait); } }; }; |
vue中使用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
< template > < div class = "main" > < p >防抖立即執行</ p > < button @ click = "click1" >點擊</ button > < br /> < p >防抖不立即執行</ p > < button @ click = "click2" >點擊</ button > < br /> < p >節流時間戳方案</ p > < button @ click = "click3" >點擊</ button > < br /> < p >節流定時器方案</ p > < button @ click = "click4" >點擊</ button > </ div > </ template > < script > import { debounce, throttleTime, throttleSetTimeout } from './utils'; export default { methods: { click1: debounce( function() { console.log('防抖立即執行'); }, 2000, true ), click2: debounce( function() { console.log('防抖不立即執行'); }, 2000, false ), click3: throttleTime(function() { console.log('節流時間戳方案'); }), click4: throttleSetTimeout(function() { console.log('節流定時器方案'); }) }, }; </ script > < style scoped lang = "scss" > * { margin: 0; font-size: 20px; user-select: none; } .main { position: absolute; left: 50%; transform: translateX(-50%); width: 500px; } button { margin-bottom: 100px; } </ style > |
解釋:
防抖:
立即執行版本:immediate為true,則點擊第一次就執行,再繼續點擊則不執行,當wait時間結束后,再點擊則生效,也就是只執行第一次。
原理:
點擊第一次不存在timeoutID,并且callNow為true,則立即執行目標代碼,點擊第二次時存在了timeoutID,并且callNow為false,所以不執行目標代碼,當wait時間結束后,把timeoutID設為null,則開始重復立即執行邏輯。
不立即執行版:immediate為false,則點擊第一次不執行,當wait時間結束后,才生效,也就是無論點擊多少次,只執行最后一次點擊事件
原理:
使用setTimeout延遲執行事件,如果多次觸發,則clearTimeout上次執行的代碼,重新開始計時,在計時期間沒有觸發事件,則執行目標代碼。
節流:
連續觸發事件時以wait頻率執行目標代碼。
效果:
以上就是Vue2.x-使用防抖以及節流的示例的詳細內容,更多關于vue 防抖及節流的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/jwyblogs/p/14454999.html