throttle.js --> 寫在utils文件夾中
function throttle(fn, gapTime) {
if (gapTime == null || gapTime == undefined) {
gapTime = 1500
}
let _lastTime = null
// 返回新的函數
return function () {
let _nowTime = + new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn.apply(this, arguments) //將this和參數傳給原函數
_lastTime = _nowTime
}
}
}
module.exports = {
throttle: throttle
}
頁面中引用
var throttle = require(../../utils/throttle)
// 點擊事件
collect: throttle.throttle(function(){})