[英]Execute function only once after multiple clicks in a row JavaScript
我有兩個數量選擇按鈕。
在用戶單擊這些按鈕中的任何一個(增加或減少數量)后,我需要運行一個函數。
但是用戶可以連續點擊幾次,我只想執行一次該功能。
就像,每次單擊后等待 1 秒以運行該功能。 如果在這 1 秒內用戶再次單擊按鈕,請重置計時器並等待另一秒以運行該功能。 當用戶在 1 秒內沒有再次點擊時,運行該函數。
在香草javascript中做到這一點的最佳方法是什么?
您只需要啟動一個 1 秒計時器並在按鈕單擊發生時將其重置。
let timer function handleClick() { clearTimeout(timer) timer = setTimeout(doSomething, 1000); } function doSomething() { let div = document.getElementById("list") let p = document.createElement("p") p.textContent = "1 second passed without a click" div.append(p) }
<!DOCTYPE html> <html> <body> <button onclick="handleClick()">Click me</button> <div id=list></div> </body> </html>
我看到兩個解決方案:
https://medium.com/nerd-for-tech/debouncing-throttling-in-javascript-d36ace200cea
你可以在 Vanilla JS 中試試這個:
const btn = document.querySelector('#btn');
const callback = event => {
console.log(event);
clearInterval(interval);
}
let interval;
btn.addEventListener('click', event => {
clearInterval(interval);
interval = setInterval( () => callback(event), 1000);
});
和 HTML:
<html>
<body>
<button id="btn">test</button>
</body>
</html>
這樣您就可以將事件實例傳遞給您的回調。
您描述了一種經典的debounce
技術。 這是一個實現:
取自https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_debounce
另一種方法是挖掘 Lodash 源代碼並從那里復制它
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
if (immediate && !timeout) func.apply(context, args);
};
}
// Avoid costly calculations while the window size is in flux.
jQuery(window).on('resize', debounce(calculateLayout, 150));
這是一篇不錯的文章和關於它的游樂場https://css-tricks.com/debouncing-throttling-explained-examples/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.