超级容易理解的函数节流(throttle)
今天搞了一个简单的写法
话不多说,直接上代码
<!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>簡易版函数节流(throttle)</title> </head> <body> <button id="mybutton">點擊執行函數</button> <script> function throttle(myfun, interval = 3000) { let canRun = true; let i = 0; return function () { if (!canRun) return; canRun = false; setTimeout(() => { myfun.apply(this, arguments); i++; console.log('可以執行操作啦!'+ i); canRun = true; }, interval); }; } var mybuttony = document.getElementById('mybutton'); mybuttony.addEventListener("click", throttle(function myfun(myarg){ console.log(myarg); })) </script> </body> </html>