您的位置:首页 > 其它

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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  understand-使用