0

I have a timeout function set up but want the countdown to restart whenever any button on the page is pressed and only functions after 2 mins of inaction:

setTimeout(function(){
    window.location.href = 'index.html';
 }, 2*60*1000);
Drew
  • 1
  • 1
    Does this answer your question? [Cancel/kill window.setTimeout() before it happens](https://stackoverflow.com/questions/452003/cancel-kill-window-settimeout-before-it-happens) – Batuhan Aug 02 '22 at 11:16
  • 1
    Does this answer your question? [Resetting a setTimeout](https://stackoverflow.com/questions/1472705/resetting-a-settimeout) – Dani Aug 02 '22 at 11:16
  • Does this answer your question? [Can someone explain the "debounce" function in Javascript](https://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript) – Ivar Aug 02 '22 at 11:18

1 Answers1

0

Sounds like you need two functions - the first to assign the timeout to a previously declared variable, and the second which is called whenever a button is clicked; it clears the timeout, and then calls the first function to restart it.

// For this example add an event listener to the button
// container - the listener listens to clicks from any
// child element
const buttons = document.querySelector('.buttons');
buttons.addEventListener('click', handleClick);

// Initialise the timer
let timer;

// Assign the timeout to the `timer` variable
// For this example it's set to five seconds so
// we can see this working in a reasonable timeframe
function startTimer() {
  timer = setTimeout(() => {
    console.log('Action complete');
  }, 5000);
}

// When a child element of `.buttons` is clicked
// check that it's a button - and if it is a button - 
// clear the timeout, and then restart it.
function handleClick(e) {
  if (e.target.matches('button')) {
    clearTimeout(timer);
    console.log('Timer reset');
    startTimer();
  }
}

startTimer();
<div class="buttons">
  <button>Button 1</button>
  <button>Button 2</button>
</div>
Andy
  • 61,948
  • 13
  • 68
  • 95