From b6eb8b075684c20917af71865066cc6a2ffab06e Mon Sep 17 00:00:00 2001 From: LCJ-MinYa <1049468118@qq.com> Date: Thu, 20 Feb 2025 15:19:22 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=98=B2=E6=8A=96=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/views/demo/ts.vue | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/views/demo/ts.vue b/src/views/demo/ts.vue index 2681bb9..cbe6c97 100644 --- a/src/views/demo/ts.vue +++ b/src/views/demo/ts.vue @@ -27,4 +27,39 @@ function useBubbleSort() { bubbleSort(arr); } useBubbleSort(); + +/** + * 第二题 1. 防抖函数 + * 防抖函数的作用是,当函数被多次调用时,只有当函数执行结束后,才会执行一次,防止函数被频繁调用。 + * 防抖函数的实现原理是,在函数执行的过程中,设置一个定时器,当函数执行结束后,清除定时器,这样就保证了函数只执行一次。 + * 应用场景一般有: + * 1. 文本输入框的实时搜索功能,用户输入字符后,函数会在输入结束后才执行,防止函数执行过于频繁。 + * 2. 页面滚动时,函数只在页面停止滚动后才执行,防止函数执行过于频繁。 + * 3. 表单提交时,函数只在用户提交表单后才执行,防止函数执行过于频繁。 + * 4. 窗口大小改变时,函数只在窗口大小改变结束后才执行,防止函数执行过于频繁。 + */ +function useDebounce() { + const debounce = (fn, delay) => { + let timer = null; + return function (...args) { + if (timer) { + clearTimeout(timer); + } + timer = setTimeout(() => { + fn.apply(this, args); + }, delay); + }; + }; + + window.addEventListener( + 'resize', + debounce(() => { + console.log('窗口大小改变了'); + }, 200) + ); +} + +/** + * 第三题 1. 节流函数 + */