js防抖和节流示例,包括html和js
时间: 2024-02-22 17:27:05 浏览: 38
好的,下面是一个防抖和节流的示例,包括HTML和JS代码:
HTML代码:
```html
<button onclick="debounceDemo()">防抖示例</button>
<button onclick="throttleDemo()">节流示例</button>
```
JS代码:
```javascript
// 防抖函数
function debounce(func, delay) {
let timer;
return function () {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
// 节流函数
function throttle(func, delay) {
let timer;
let lastTime = 0;
return function () {
const context = this;
const args = arguments;
const nowTime = Date.now();
if (nowTime - lastTime > delay) {
lastTime = nowTime;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
}
};
}
// 防抖示例
function debounceDemo() {
const debounceFunc = debounce(() => {
console.log('防抖示例');
}, 1000);
debounceFunc();
debounceFunc();
debounceFunc();
}
// 节流示例
function throttleDemo() {
const throttleFunc = throttle(() => {
console.log('节流示例');
}, 1000);
throttleFunc();
throttleFunc();
throttleFunc();
}
```
在这个示例中,我们定义了一个防抖函数和一个节流函数。然后,我们编写了两个示例函数,一个用于演示防抖,另一个用于演示节流。在这两个示例函数中,我们使用了防抖函数和节流函数来确保函数不会被频繁调用。最后,在HTML代码中,我们定义了两个按钮,分别用于触发防抖示例和节流示例。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)