Skip to content

函数工具 (Function)

@pt/utils/modules/function 提供了函数处理相关的工具函数。

debounce

创建一个防抖函数。

typescript
import { debounce } from '@pt/utils/modules/function';

const handleSearch = debounce((query: string) => {
  console.log('Searching for:', query);
}, 300);

// 快速调用多次,只会在最后一次调用后300ms执行一次
input.addEventListener('input', (e) => {
  handleSearch(e.target.value);
});

throttle

创建一个节流函数。

typescript
import { throttle } from '@pt/utils/modules/function';

const handleScroll = throttle(() => {
  console.log('Scrolling...');
}, 100);

// 每100ms最多执行一次
window.addEventListener('scroll', handleScroll);

once

创建一个只执行一次的函数。

typescript
import { once } from '@pt/utils/modules/function';

const initialize = once(() => {
  console.log('初始化...');
});

// 多次调用也只会执行一次
initialize(); // 输出: '初始化...'
initialize(); // 无输出

Released under the MIT License.