add util function throttle and debounce
Showing
1 changed file
with
32 additions
and
1 deletions
@@ -131,6 +131,35 @@ const miniVersion = function (miniVersion) { | @@ -131,6 +131,35 @@ const miniVersion = function (miniVersion) { | ||
131 | return false; | 131 | return false; |
132 | }; | 132 | }; |
133 | 133 | ||
134 | +const debounce = function(idle, action) { // 函数去抖动,超过一定时间才会执行,如果周期内触发,重置计时器 | ||
135 | + let last; | ||
136 | + | ||
137 | + return function() { | ||
138 | + let args = arguments; | ||
139 | + | ||
140 | + if (last) { | ||
141 | + clearTimeout(last); | ||
142 | + } | ||
143 | + last = setTimeout(() => { | ||
144 | + action.apply(this, args); | ||
145 | + }, idle); | ||
146 | + }; | ||
147 | +}; | ||
148 | + | ||
149 | +const throttle = function(delay, action) { // 函数节流器,定义函数执行间隔,按频率触发函数 | ||
150 | + let last = 0; | ||
151 | + | ||
152 | + return function() { | ||
153 | + let args = arguments; | ||
154 | + let curr = +new Date(); | ||
155 | + | ||
156 | + if (curr - last > delay) { | ||
157 | + action.apply(this, args); | ||
158 | + last = curr; | ||
159 | + } | ||
160 | + }; | ||
161 | +}; | ||
162 | + | ||
134 | export default { | 163 | export default { |
135 | getImgHost, | 164 | getImgHost, |
136 | getImgUrl, | 165 | getImgUrl, |
@@ -138,5 +167,7 @@ export default { | @@ -138,5 +167,7 @@ export default { | ||
138 | visibilitychange, | 167 | visibilitychange, |
139 | getChannel, | 168 | getChannel, |
140 | replaceHttp, | 169 | replaceHttp, |
141 | - miniVersion | 170 | + miniVersion, |
171 | + debounce, | ||
172 | + throttle | ||
142 | }; | 173 | }; |
-
Please register or login to post a comment