js防抖函数

139 阅读1分钟

函数防抖是指对于在事件被触发n秒后再执行的回调,如果在这n秒内又重新被触发

               /**
		 * 防抖函数
		 * await间隔时间
		 * immediate是否立即执行
		 * fn执行函数
		 */
		function debounce(fn, await = 500, immediate = true) {
			/**
			 * timer标记
			 */
			let timer, rs;
			let debounced = function(...args) {
				timer && clearTimeout(timer)
				if (immediate) {
					//异常处理线缓存使得防抖得以继续
					let callnow = !timer;
					timer = setTimeout(() => {
						timer = null
					}, await)
					callnow && (rs = fn.apply(this, args))

				} else {
					timer = setTimeout(() => {
						fn.apply(this, args)
					}, await)
				}
				return rs
			}
			/**
			 * 取消函数执行
			 */
			debounced.cancel = function() {
				clearTimeout(timer)
			}
			return debounced
		}