underscore.js 源码分析(十一)
throttle debounce once after beforethrottle
函数节流_.throttle(function, wait, [options])使用 throttle 函数用于节流操作, 目的是对于重复执行的函数,最多每隔 wait 毫秒调用一次这个函数。源码分析
1 | /* |
1 | function getIndex() { |
1 | function throttle (func, wait, options) { |
debounce
_.debounce(function, wait, [immediate])debounce 函数用于函数防抖: 函数防抖的意思是将延迟函数的执行(真正的执行)在函数最后一次调用的时刻的 wait 毫秒之后进行执行。当函数重复调用的时候,函数执行只是发生在最后一次调用的 wait 毫秒之后进行执行。自己写的:1 | function debounce(func, wait, immediate) { |
源码解析
1 | _.debounce = function(func, wait, immediate) { |
later 函数如下:1 | let later = function () { |
wait 时间之内,函数被调用了第二次,程序会在函数调用第二次的时候记录下时间,这时候 wait 时间之后调用函数的时候,第一次调用的函数不会被触发,程序在 later 函数中继续延迟第二次调用函数距离上一次调用需要的时间,这样,最终,第二次函数也是和第一次函数调用的结果是相同点的,都是在延迟了wait 时间之后被调用。once
创建一个只能调用一次的函数。即使函数被调用一次,也只是返回第一次被调用的结果。使用 once 是当 before 方法中 count 等于2的情况下进行执行的函数;1 | // 向 befor 函数中传递参数为 2 |
before
_.before(count, function)创建一个函数,调用不超过 count 次, 当count已经被达到的时候,最后一次调用的结果被记住并被返回。自己写的:1 | /* |
1 | _.before = function (times, func) { |
after
_.after(count, function)使用 _.after 的作用是创建一个函数,只有调用 count 次之后才能得到效果。1 | /* |