按照防抖函数和节流函数的定义手动实现该效果,当然功能并不完善还有待改进,详细的请参考原文链接:js 函数的防抖(debounce)与节流(throttle)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="box" style="width: 200px;height: 200px;background: #eee;"></div>
<script>
let box = document.getElementById('box')
//防抖函数-开始触发时执行
/* let flag = true
box.onmousemove = function () {
if(flag){
console.log(111)
flag = false
}
} */
//防抖函数-触发结束时执行
/* box.onmouseenter = function () {
let flag = true
box.onmouseleave = function () {
if(flag){
console.log(111)
flag = false
}
}
} */
//节流
box.onmouseenter = function () {
let flag = true
setInterval(function () {
if(flag){
console.log(123)
}
}, 2000)
box.onmouseleave = function () {
flag = false
}
}
</script>
</body>
</html>
网友评论