underscore方法--debounce
2017-12-27 13:58
99 查看
用法
_.debounce(function, wait, [immediate])Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on.
上面是官方文档的解释,意思是,_.bounce()方法会将传入的函数变成一个debounced函数并返回,这个函数在一定的时间里只能被执行一次,即使被多次触发。官方文档举了一个例子说markdown就是如此,会等用户结束输入之后才会渲染layout,而不是一直不停的执行渲染命令。最后一个参数immediate如果加上的话,函数会在触发事件发生的开头而不是结尾触发。
window.onclick = _.debounce(function(){console.log(1111)}, 1000)
这个时候无论怎么点击,一秒之内只能打印一个结果。
源码
// Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, result; var later = function(context, args) { timeout = null; if (args) result = func.apply(context, args); }; var debounced = restArgs(function(args) { if (timeout) clearTimeout(timeout); if (immediate) { var callNow = !timeout; timeout = setTimeout(later, wait); if (callNow) result = func.apply(this, args); } else { timeout = _.delay(later, wait, this, args); } return result; }); debounced.cancel = function() { clearTimeout(timeout); timeout = null; }; return debounced; };
相关文章推荐
- Underscore模版引擎的使用-template方法
- underscore方法使用
- underscore 源码解读之 bind 方法的实现
- 【跟着子迟品 underscore】常用类型判断以及一些有用的工具方法
- underscore的几个集合的方法操作【5】
- underscore的对象的方法操作【6】
- debounce函数让一个方法在一定时间内只能执行一次
- underscore几个数组的方法【3】
- underscore 的 debounce 的实现
- 【跟着子迟品 underscore】JavaScript 数组展开以及重要的内部方法 flatten
- 浅谈 underscore 内部方法 group 的设计原理
- 【跟着子迟品 underscore】如何优雅地写一个『在数组中寻找指定元素』的方法
- underscore 的debounce
- underscore里面的debounce与throttle
- JavaScript学习笔记——underscore操作对象的方法
- AR9331出现connect-debounce failed,port 1 disabled解决方法备忘
- AR9331出现connect-debounce failed,port 1 disabled解决方法备忘
- 模板方法模式实践
- ASP.NET页面跳转的几种方法
- Python 关于bytes类方法对数字转换的误区, Json的重要性