|
@@ -0,0 +1,87 @@
|
|
|
+<!DOCTYPE html>
|
|
|
+<html lang="en">
|
|
|
+
|
|
|
+<head>
|
|
|
+ <meta charset="UTF-8">
|
|
|
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
|
+ <title>Document</title>
|
|
|
+ <style>
|
|
|
+ #box {
|
|
|
+ width: 200px;
|
|
|
+ height: 200px;
|
|
|
+ text-align: center;
|
|
|
+ line-height: 200px;
|
|
|
+ font-size: 30px;
|
|
|
+ font-weight: bold;
|
|
|
+ color: #ff0;
|
|
|
+ background: #f00;
|
|
|
+ margin: 20px 0;
|
|
|
+ }
|
|
|
+ </style>
|
|
|
+</head>
|
|
|
+
|
|
|
+<body>
|
|
|
+ <!--
|
|
|
+ 节流:
|
|
|
+ 规定时间内,只能触发一次函数,如果在规定时间内再次触发函数
|
|
|
+ 则不执行,必须等函数完成后才会再次执行
|
|
|
+ 场景:
|
|
|
+ 1.高频的按钮点击
|
|
|
+ 2.滚动加载
|
|
|
+ -->
|
|
|
+ <div>
|
|
|
+
|
|
|
+ <div id="box"></div>
|
|
|
+ <div id="box"></div>
|
|
|
+ <div id="box"></div>
|
|
|
+ <div id="box"></div>
|
|
|
+ <div id="box"></div>
|
|
|
+ <div id="box"></div>
|
|
|
+ <div id="box"></div>
|
|
|
+ <div id="box"></div>
|
|
|
+ <div id="box"></div>
|
|
|
+ <div id="box"></div>
|
|
|
+ <div id="box"></div>
|
|
|
+ </div>
|
|
|
+ <script>
|
|
|
+ var box = document.getElementById("box");
|
|
|
+ let i = 0;
|
|
|
+ function Count() {
|
|
|
+ box.innerText = i++;
|
|
|
+ }
|
|
|
+ // 时间戳:new Date().getTime() / Date.now()
|
|
|
+ // 记录上次时间 每次触发时 判断当前时间与上次时间相差是否超过间隔时间
|
|
|
+ // function throttle(fn,delay) {
|
|
|
+ // let lastTime = 0
|
|
|
+ // return function() {
|
|
|
+ // let now = Date.now();
|
|
|
+ // setTimeout(function() {
|
|
|
+ // if(now - lastTime >= delay) {
|
|
|
+ // fn();
|
|
|
+ // lastTime = now;
|
|
|
+ // }
|
|
|
+ // },delay)
|
|
|
+ // }
|
|
|
+ // }
|
|
|
+ // 定时器
|
|
|
+ // 设置定时器 在间隔时间后执行回调函数 并在执行后 重置定时器
|
|
|
+ function throttle(fn, delay) {
|
|
|
+ let timer = null;
|
|
|
+ return function () {
|
|
|
+ if (!timer) {
|
|
|
+ timer = setTimeout(function () {
|
|
|
+ fn();
|
|
|
+ timer = null;
|
|
|
+ }, delay)
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ box.addEventListener('click', throttle(Count, 3000));
|
|
|
+ const handleScroll = throttle(function () {
|
|
|
+ console.log("滚动位置", window.screenY);
|
|
|
+ }, 1000)
|
|
|
+ window.addEventListener('scroll', handleScroll)
|
|
|
+ </script>
|
|
|
+</body>
|
|
|
+
|
|
|
+</html>
|