When you want to do something repeating at a set interval, setInterval
may be a better way to go. It will call a method after every X milliseconds if you don't cancel it.
Here is a basic example of reseting the interval whenever a button is clicked. In the log you will see that when you don't click the button a new log line appears every 5 seconds. When you click on the button the next line will take longer to appear after which they will appear again every 5 seconds.
I used 5 seconds instead of 30 so you don't have to wait that long to see the effect of pressing the button.
const
resetButton = document.getElementById('reset'),
confirmationMessage = document.getElementById('confirmation'),
intervalDuration = 5000;
let
intervalId = null
lastCallTime = new Date();
function resetInterval() {
// Stop the current interval...
clearInterval(intervalId);
// and start a new interval.
startInterval();
}
function startInterval() {
// Set an interval, it will call logTimeSinceLastCall every X seconds.
intervalId = setInterval(() => {
logTimeSinceLastCall();
}, intervalDuration);
}
function logTimeSinceLastCall() {
// Hide the message that the interval has been reset.
confirmationMessage.classList.add('hidden');
const
// Get the current time.
now = new Date(),
// Substract the time from the last call, the difference is the number of milliseconds passed.
diff = now.getTime() - lastCallTime.getTime();
// Log a line to the console for some visual feedback.
console.log(`Last call was ${diff}ms ago`);
// Update the time stamp of the last time this method was called.
lastCallTime = now;
}
function onResetClicked(event) {
resetInterval();
// Show the message that the button has been clicked.
confirmationMessage.classList.remove('hidden');
}
// Whenever the button is clicked, reset the interval.
resetButton.addEventListener('click', onResetClicked);
// Start the initial interval.
startInterval();
.hidden {
display: none;
}
<button type="button" id="reset">Reset interval</button>
<p id="confirmation" class="hidden">
The interval has been reset.
</p>