例子描述:實時顯示輸入框的內容javascript
基礎版:html
html頁面代碼:java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script src="utils.js"></script> <script> $(function(){ $('#ipt').on('keyup', throttle(function(){ $('#text').text($(this).val()); }, 500)) }) </script> </head> <body> <input id="ipt" type="text" placeholder="請輸入..."> <p id="text"></p> </body> </html>
把throttle替換成debounce試試防抖效果。jquery
utils.jsapp
// 防抖函數 function debounce(fn) { let timeout = null; return function () { clearTimeout(timeout); timeout = setTimeout(() => { fn.call(this, arguments); }, 1000); } } // 節流函數 function throttle (fn, delay) { var prev = Date.now(); return function () { var args = arguments; var now = Date.now(); if (now - prev >= delay) { fn.apply(this, args); prev = Date.now(); } } }
在這個例子中,節流會比防抖效果更好一些。函數
另外一個例子:一個Vue表單提交防抖的實用例子post