You can not select more than 25 topics
			Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
		
		
		
		
		
			
		
			
				
					34 lines
				
				702 B
			
		
		
			
		
	
	
					34 lines
				
				702 B
			| 
											3 years ago
										 | 'use strict'; | ||
|  | 
 | ||
|  | /** | ||
|  |  * Throttle decorator | ||
|  |  * @param {Function} fn | ||
|  |  * @param {Number} freq | ||
|  |  * @return {Function} | ||
|  |  */ | ||
|  | function throttle(fn, freq) { | ||
|  |   let timestamp = 0; | ||
|  |   const threshold = 1000 / freq; | ||
|  |   let timer = null; | ||
|  |   return function throttled(force, args) { | ||
|  |     const now = Date.now(); | ||
|  |     if (force || now - timestamp > threshold) { | ||
|  |       if (timer) { | ||
|  |         clearTimeout(timer); | ||
|  |         timer = null; | ||
|  |       } | ||
|  |       timestamp = now; | ||
|  |       return fn.apply(null, args); | ||
|  |     } | ||
|  |     if (!timer) { | ||
|  |       timer = setTimeout(() => { | ||
|  |         timer = null; | ||
|  |         timestamp = Date.now(); | ||
|  |         return fn.apply(null, args); | ||
|  |       }, threshold - (now - timestamp)); | ||
|  |     } | ||
|  |   }; | ||
|  | } | ||
|  | 
 | ||
|  | export default throttle; |