Reputation: 47
I have a function named showAlert that displays an alert. I have used the setTimeout function to delay it by 5 seconds. I have a button that should increase the delay by an additional 5 seconds. How can I do this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Timer</title>
</head>
<body>
<button>Increment delay by 5 seconds</button>
<script>
var timer = 5000;
function showAlert(){
alert("Hello world");
}
setTimeout(showAlert, timer);
</script>
</body>
</html>
Upvotes: 1
Views: 627
Reputation: 712
You cannot, but you can cancel the previously scheduled job and start another.
<script>
var job = undefined;
function showAlert(){
alert("Hello world");
}
function onButtonClick(){
if (!!job) {
clearTimeout(job);
}
job = setTimeout(showAlert, timer);
}
</script>
Upvotes: 0
Reputation: 370619
You'll have to clear the timeout, calculate the new time until the callback should fire, and call setTimeout
again.
I'll change the delay time to 1 second instead of 5 seconds to illustrate more quickly in the snippet below:
let callbackTimestamp = Date.now() + 1000;
const cb = () => {
timeoutId = null;
console.log('hello');
};
let timeoutId = setTimeout(cb, 1000);
document.querySelector('button').addEventListener('click', () => {
if (!timeoutId) return;
clearTimeout(timeoutId);
callbackTimestamp += 1000;
timeoutId = setTimeout(cb, callbackTimestamp - Date.now());
});
<button>Increment delay by 1 second</button>
(in your real code, change each 1000
to 5000
)
Upvotes: 2