函数防抖与节流
underscore.js提供了很多很有用的函数,今天想说说其中的两个。这两个函数都用于限制函数的执行
debounce
在解释这个函数前,我们先从一个例子看下这个函数的使用场景。假设我们网站有个搜索框,用户输入文本我们会自动联想匹配出一些结果供用户选择。我们可能首先想到的做法就是监听keypress事件,然后异步去查询结果。这个方法本身是没错的,但是如果用户快速的输入了一连串的字符,假设是10个字符,那么就会在瞬间触发了10次的请求,这无疑不是我们想要的。我们想要的是用户停止输入的时候才去触发查询的请求,这时候函数防抖可以帮到我们。
函数防抖就是让某个函数在上一次执行后,满足等待某个时间内不再触发此函数后再执行,而在这个等待时间内再次触发此函数,等待时间会重新计算。
我们先看下underscore.js里相关函数的定义:
_.debounce(function, wait, [immediate])
// 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, args, context, timestamp, result