6 changed files with 57 additions and 4 deletions
@ -1,3 +1,4 @@ |
|||
export * from "./date"; |
|||
export * from "./common"; |
|||
export * from "./debounce"; |
|||
export * from "./throttle"; |
|||
|
@ -0,0 +1,19 @@ |
|||
<template> |
|||
<n-button @click="clickFn">点击</n-button> |
|||
<div> |
|||
<h4>输出结果</h4> |
|||
<div v-for="(item, index) in result" :key="index"> |
|||
{{ item }} |
|||
</div> |
|||
</div> |
|||
</template> |
|||
<script lang="ts" setup> |
|||
import { throttle } from "@xyx-utils/core/throttle"; |
|||
import { ref } from "vue"; |
|||
|
|||
const result = ref([]) |
|||
const clickFn = throttle(()=>{ |
|||
result.value.push("poll") |
|||
}, 1000) |
|||
</script> |
|||
<style lang="scss" scoped></style> |
@ -0,0 +1,9 @@ |
|||
--- |
|||
title: 节流 |
|||
category: 工具 |
|||
--- |
|||
|
|||
<preview path="./demo.vue" title="时间" description="时间按指定格式输出"></preview> |
|||
|
|||
当频繁点击时,每一秒执行一次 |
|||
|
@ -0,0 +1,17 @@ |
|||
export function throttle<T extends any[], R = void>(fn: (...argu: T) => R, interval: number = 200) { |
|||
let last; |
|||
let timer: ReturnType<typeof setTimeout> | void; |
|||
return function (this: void, ...argu: T) { |
|||
const now = +new Date(); |
|||
if (last && now - last < interval) { |
|||
timer && clearTimeout(timer); |
|||
timer = setTimeout(() => { |
|||
last = now; |
|||
fn.apply(this, argu); |
|||
}, interval); |
|||
} else { |
|||
last = now; |
|||
fn.apply(this, argu); |
|||
} |
|||
}; |
|||
} |
Loading…
Reference in new issue