写个js节流
节流(throttle)是一种优化性能的技术,在一定时间内只执行一次函数,而不是每次事件都执行函数。
实现一个简单的节流函数可以按照以下步骤:
-
定义一个变量来存储上一次执行函数的时间戳。
-
定义一个函数来判断当前时间是否超过上一次执行函数的时间戳加上指定的时间间隔。
-
如果当前时间已经超过时间间隔,则执行函数,并更新上一次执行函数的时间戳。
-
在事件处理函数中调用节流函数。
以下是一个简单的实现:
function throttle(func, delay) {
let lastTime = 0;
return function() {
const now = new Date().getTime();
if (now - lastTime > delay) {
func.apply(this, arguments);
lastTime = now;
}
}
}
使用方式如下:
function handleClick() {
console.log('Button clicked');
}
const throttledClick = throttle(handleClick, 1000);
document.querySelector('button').addEventListener('click', throttledClick);
这样,当用户点击按钮时,事件处理函数 handleClick 会被节流函数 throttle 包装,每次点击后只有在超过 1 秒后才会执行一次
原文地址: https://www.cveoy.top/t/topic/cOKx 著作权归作者所有。请勿转载和采集!