函數節流(throttle):函數在一段時間內多次觸發只會執行第一次,在這段時間結束前,不管觸發多少次也不會執行函數。
1.添加utils.js文件
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 }
2.在需要使用的頁面引入utils.js
const util = require('../../utils/util.js')
使用
handle: util.throttle(function () { })