UNPKG

xxm-test-js

Version:

xxm-js通用js工具(utils)库

65 lines 1.79 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.throttle = throttle; /** * 创建一个节流函数,该函数会在最后一次调用后的指定时间后停止执行。 * Copyright (c) 2024 xxm * * @param func - 需要节流的函数。 * @param limit - 节流的时间间隔,单位是毫秒。 * @returns 一个新的函数,该函数会在节流时间内限制原函数的执行。 * @example * ```vue * <template> * <div id="app"></div> * </template> * * <script> * import { throttle } from 'xxm-test-js'; * * export default { * name: 'App', * data() { * return { * throttledHandleScroll: null * } * }, * methods: { * handleScroll() { * console.log('页面正在滚动...'); * } * }, * mounted() { * this.throttledHandleScroll = throttle(this.handleScroll, 200); * window.addEventListener('scroll', this.throttledHandleScroll); * }, * beforeDestroy() { * window.removeEventListener('scroll', this.throttledHandleScroll); * } * }; * </script> * ``` */ function throttle(func, limit) { let lastFunc = null; let lastRan = 0; return function (...args) { const context = this; const time = Date.now(); if (time - lastRan >= limit) { func.apply(context, args); lastRan = time; lastFunc = null; } else { if (lastFunc !== null) { clearTimeout(lastFunc); // 统一使用 clearTimeout } lastFunc = setTimeout(() => { func.apply(context, args); lastRan = Date.now(); // 使用实际执行时间更新 lastRan }, limit); } }; } //# sourceMappingURL=throttle.js.map