96 lines
2.5 KiB
HTML
96 lines
2.5 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="zh">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>节流</title>
|
||
</head>
|
||
<body>
|
||
<div style="height: 100px;width: 100px;">
|
||
</div>
|
||
<button>点击我更换颜色</button>
|
||
<script>
|
||
function throttle(fun, delay){
|
||
var flag = true // 是否可以执行
|
||
return function(){
|
||
if(flag){
|
||
var args = arguments
|
||
var context = this
|
||
fun.apply(context, args)
|
||
flag = false
|
||
setTimeout(function(){
|
||
flag = true
|
||
}, delay)
|
||
}
|
||
}
|
||
}
|
||
|
||
function lastThrottle(fun, delay) {
|
||
var timer = 0
|
||
return function () {
|
||
if(timer) return
|
||
var args = arguments
|
||
var context = this
|
||
timer = setTimeout(function () {
|
||
fun.apply(context, args)
|
||
timer = 0
|
||
},delay)
|
||
}
|
||
}
|
||
|
||
function lastThrottleByTime(fun, delay) {
|
||
var pre = 0
|
||
return function () {
|
||
var cur = Date.now() // 获取当前的时间戳
|
||
if(cur - pre > delay) {
|
||
var args = arguments
|
||
var context = this
|
||
fun.apply(context, args)
|
||
pre = cur
|
||
}
|
||
}
|
||
}
|
||
|
||
function firstAndLastThrottle(fun, delay) {
|
||
var pre = 0
|
||
var timer = 0
|
||
var _delay = delay + 100 // 防抖用的时间间隔,比节流大0.1秒,因为人对0.1秒的延迟无感知
|
||
return function () {
|
||
var args = arguments
|
||
var context = this
|
||
var cur = Date.now() // 获取当前的时间戳
|
||
if(cur - pre > delay) {
|
||
fun.apply(context, args)
|
||
pre = cur
|
||
}
|
||
clearTimeout(timer)
|
||
timer = setTimeout(() => {
|
||
fun.apply(context, args)
|
||
}, _delay);
|
||
}
|
||
}
|
||
|
||
function setBgColor(el){
|
||
let r = Math.floor(Math.random()*256)
|
||
let g = Math.floor(Math.random()*256)
|
||
let b = Math.floor(Math.random()*256)
|
||
div.style.backgroundColor = `rgb(${r},${g},${b})`
|
||
}
|
||
let div = document.querySelector("div")
|
||
let button = document.querySelector("button")
|
||
setBgColor(div) // 初始化
|
||
// button.addEventListener("click",throttle(function(){
|
||
// setBgColor(div)
|
||
// },250))
|
||
// button.addEventListener("click",lastThrottle(function(){
|
||
// setBgColor(div)
|
||
// },2000))
|
||
// button.addEventListener("click",lastThrottleByTime(function(){
|
||
// setBgColor(div)
|
||
// },1000))
|
||
button.addEventListener("click",firstAndLastThrottle(function(){
|
||
setBgColor(div)
|
||
},250))
|
||
</script>
|
||
</body>
|
||
</html> |