/** * Only allow the function run once * @param {[Function]} fun The function need to be changed */ functiononce(fun) { returnfunction(...args) { if (fun) { const ret = fun.apply(this, args); fun = null; return ret; } } }
throttle函数
throttle函数,即节流函数。在特定时间里只运行一次,丢弃之后的执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * Only run once in the specified time range. * @param {[Function]} fun The function need to be changed * @param {[Number]} ms The time need to be throttle */ functionthrottle(fun, ms) { let throttleTimer = null; returnfunction(...args) { if (!throttleTimer) { throttleTimer = setTimeout(function() { const ret = fun.apply(this, args); throttleTimer = null; return ret; }, ms) } } }
debounce函数
防抖函数,在特定时间段内取消重复的运行,只会运行最后一次。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * Only run the last time in the specified time range. * @param {[Function]} fun The function need to be changed * @param {[Number]} ms The time need to be debounced */ functiondebounce(fun, ms) { let debounceTimer = null; returnfunction(...args) { if (debounceTimer) { clearTimeout(debounceTimer); } debounceTimer = setTimeout(function() { const ret = fun.apply(this, args); return ret; }, ms) } }
wait函数(工具函数)
setTimeout函数的Promise版重新组织方式
1 2 3 4 5 6 7 8 9
/** * * @param {number} duration The time need to waiting. */ functionwait(duration) { returnnewPromise((resolve, reject) => { setTimeout(resolve, duration); }) }