JavaScript Click Timeout: Clear Previous Timeout on New Click
<p>To achieve your goal of setting a timeout on click and clearing the last timeout if another click is triggered, you can use JavaScript. Here's an example code snippet that demonstrates this behavior: html </p>
<!DOCTYPE html> 
<html> 
<head> 
<title>Set Timeout on Click</title> 
</head> 
<body> 
<p><button id="myButton">Click me</button> </p>
<script> 
let timeoutId; 
function handleClick() { 
// Clear the last timeout if it exists 
clearTimeout(timeoutId); 
// Set a new timeout 
timeoutId = setTimeout(() => { 
console.log("Timeout function executed"); 
// Perform your desired actions here after the timeout 
}, 2000); 
} 
const button = document.getElementById("myButton"); 
button.addEventListener("click", handleClick); 
</script> 
</body> 
</html>  
<p>In this example, a button element with the id "myButton" is created. The JavaScript code defines a <code>handleClick</code> function that is called whenever the button is clicked. Inside the function, <code>clearTimeout</code> is used to clear the last timeout (if any) before setting a new timeout using <code>setTimeout</code>. The timeout function will be executed after 2000 milliseconds (2 seconds) unless another click occurs and the timeout is cleared and reset. </p>
<p>Feel free to modify the code to suit your specific requirements, such as changing the timeout duration or performing different actions inside the timeout function.</p>
原文地址: https://www.cveoy.top/t/topic/qf90 著作权归作者所有。请勿转载和采集!