<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>点我获取时间戳(防抖)</p>
<div style="width: 100px;height:100px;background-color: aqua;">鼠标放上来随机改变数字(节流)</div>
<script>
let p = document.querySelector('p');
let div = document.querySelector('div')
/**
* 防抖
* fn ===> 要执行的函数
* delay ==> 延迟的毫秒数
* */
function debounce(fn, delay) {
// 定时器
let timer;
return function () {
clearTimeout(timer)
timer = setTimeout(function () {
fn.apply(this, arguments)
}, delay)
}
}
p.addEventListener('click', debounce(function (e) {
console.log(this)
let date = new Date().getTime()
p.innerHTML = date;
}, 1000))
/**
* 节流
* fn ===> 要执行的函数
* delay ==> 延迟的毫秒数
* */
function throttle(fn, delay) {
let run = true
return function () {
if (!run) {
return
}
run = false
setTimeout(function () {
fn.apply(this, arguments)
run = true
}, delay)
}
}
div.addEventListener('mousemove', throttle(function (e) {
div.innerHTML = Math.random();
}, 1000))
</script>
</body>
</html>
防抖节流函数实现
最新推荐文章于 2024-07-11 16:38:48 发布