First, we quickly slide down from the top, and output the index in the mouse move event
enters(index) {
this.currentIndex=index;
console.log(index);
}
This will only print these few
Cause: This is because it is too fast, and the browser has not responded yet.
First understand anti-shake and throttling:
Simple understanding: throttling is equivalent to skill cd, and anti-shake is equivalent to returning to the city.
(1) Realize anti-shake
First look at a code:
<!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>防抖</title>
</head>
<body>
<p>
请你输入搜索的内容:<input type="text">
</p>
</body>
<script>
let input = document.querySelector('input');
input.oninput = function() {
console.log('ajax发请求');
}
</script>
</html>
I want to send an ajax request after typing. I can use closure + timer, or Lodash. The first method has been mentioned before. See blog post: JS Taobao search box anti-shake strategy_eating fish balls Shen Shen's blog-CSDN blog_Search box anti-shake , so let's take a look at how to do the second one. See the official website for installation: Lodash Introduction | Lodash Chinese Documentation | Lodash Chinese Network (lodashjs.com)
code show as below:
<!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>防抖</title>
<!-- 引入Lodash -->
<script src="./lodash.js"></script>
</head>
<body>
<p>
请你输入搜索的内容:<input type="text">
</p>
</body>
<script>
let input = document.querySelector('input');
// lodash插件:里面封装函数的防抖与节流的业务【闭包+延时器】
// lodash对外暴露_
// _有一个防抖函数debounce 第一个参数是函数,第二个参数是延时毫秒数
input.oninput = _.debounce(function() {
console.log('ajax发请求');
}, 1000);
</script>
</html>
(2) Realize throttling
Look directly at the code:
<!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>节流</title>
<script src="./lodash.js"></script>
</head>
<body>
<div>
<h1>我是计数器<span>0</span></h1>
<button>点击我+1</button>
</div>
</body>
<script>
// 获取节点
let span = document.querySelector('span');
let button = document.querySelector('button');
let count = 0;
// 现在要求,在一秒以内,数字只能+1
button.onclick = _.throttle(function() {
count++;
span.innerHTML = count;
}, 1000)
</script>
</html>
Summarize: