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);
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);
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>