![](/img/trans.png)
[英]Why is “console.log” being executed every time the function is called, but “return” is executed only once?
[英]Why does console.log("Called"); is called only once inside the debounce function?
在下面的代碼中為什么 console.log("Called"); 盡管在每個 keyup 事件上一次又一次地調用 debounce 函數,但只會出現一次
const txt = document.getElementById("text"); let label = document.getElementById("label"); function debounce(fun,delay) { let time; console.log("Called"); return function(args) { if(time) { clearTimeout(time); } time = setTimeout(() => { fun(args); },delay); } } function callback(e) { label.innerHTML = e.target.value; } txt.addEventListener("keyup", debounce(callback,700)); </script>
<html> <body> <input type="text" id="text" placeholder="Enter something..."><br /> <label id="label"></label> </body> </html>
?
它在設置事件偵聽器時被調用。 甚至在任何 keyup 事件之前。 如果要在調用函數時記錄。 將其記錄在從 debounce 返回的函數中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.