js 函式防抖節流
阿新 • • 發佈:2021-12-16
<!DOCTYPE html> <html lang="zh"> <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></title> </head> <body> <input type="text" id="input" /> </body> <script> // 函式防抖 function debounce(fn, Interval) { let timer; return (event) => { if (timer) { return false } timer = setTimeout(() => { clearTimeout(timer) timer = null fn(event) }, Interval) } } window.onresize = debounce(function(event) { console.log(event) }, 1000) // 節流 function throttle(fn, Interval) { let timer return () => { clearTimeout(timer) timer = setTimeout(fn, Interval) } } let input = document.getElementById('input') input.oninput = throttle(function(event) { console.log(input.value) }, 1000) </script> </html>