js防抖
2021/7/23 6:08:47
本文主要是介绍js防抖,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
初级版
<!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"> <script src="../js/jquery-3.6.0.min.js"></script> <title>Document</title> <script> $(() => { let t; $('input').on('input', (event) => { if (t != null) { clearTimeout } t = setTimeout(() => { console.log(event.currentTarget.value); }, 500); }) }); //或者 window.onload = function() { let inp = document.querySelector("input") let t = null; inp.oninput = function() { if (t !== null) { clearTimeout(t) } t = setTimeout(() => { console.log(this.value); }, 500); } } </script> </head> <body> <input type="text"> </body> </html>
晋级版
window.onload = function() { let inp = document.querySelector("input") let t = null; inp.oninput = debounce(function() { console.log(this.value) }, 500) function debounce(fn, delay) { let t; return function() { if (t != null) { clearTimeout(t) } t = setTimeout(() => { fn.call(this); }, delay); } } }
节流
<!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"> <script src="../js/jquery-3.6.0.min.js"></script> <title>Document</title> <script> window.onload = function() { let flag = true window.onscroll = function() { if (flag) { setTimeout(() => { console.log('123'); flag = true }, 500); } flag = false; } } </script> </head> <body style="height: 2000px;"> <input type="text"> </body> </html>
进阶
<script> window.onload = function() { window.onscroll = throttle(() => { console.log('qweqwe'); }, 500) function throttle(fn, delay) { let flag = true return function() { if (flag) { setTimeout(() => { fn.call(this) flag = true }, 500); flag = false; } } } } </script>
这篇关于js防抖的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-24Vue CLI多环境配置学习:从入门到实践
- 2024-11-24Vue CLI多环境配置学习:新手入门教程
- 2024-11-24Vue CLI学习:初学者指南
- 2024-11-24Vue CLI学习:从入门到上手的简单教程
- 2024-11-24Vue3+Vite学习:从零开始的前端开发之旅
- 2024-11-24Vue3阿里系UI组件学习入门教程
- 2024-11-24Vue3的阿里系UI组件学习入门指南
- 2024-11-24Vue3公共组件学习:新手入门教程
- 2024-11-24Vue3公共组件学习入门指南
- 2024-11-24vue3核心功能响应式变量学习