Reputation: 71
I have two buttons. The first one lets appear an alert with a delay of 3 seconds and another one 3 seconds later. The second button must be able to pause the setTimeout
function.
So when the first alert has appeared and I click on 'pause' the second should not show up. I know I'm close to the solution, but it still doesn't work. My code is:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#start").click(function () {
setTimeout(myFunction, 3000);
setTimeout(myFunction, 6000);
});
$("#stop").click(function () {
$("myFunction").stop();
});
});
function myFunction() {
alert('Hello');
}
</script>
</head>
<body>
<p>
<button id="start">Start</button>
<button id="stop">Pause</button>
</p>
</body>
</html>
Upvotes: 0
Views: 92
Reputation: 96
The best way to do this is to check with cookies.
This is how I would do this:
1. Before starting alert check if there is a cookie named for example "some_cookie" and it's value; 2. When you click on "pause" it stores value "1" in to "some_cookie"; 3. If value is "0" than run;
Easy. just busy to write you code. If you need it, just tell me. I'll write.
Upvotes: -1
Reputation: 337610
To achieve this you need to store a reference to your setTimeout()
calls and then call clearTimeout()
on them when needed. Try this:
$(document).ready(function() {
var timers = [];
$("#start").click(function(){
timers.push(setTimeout(myFunction, 3000));
timers.push(setTimeout(myFunction, 6000));
});
$("#stop").click(function(){
timers.forEach(function(timer) {
clearTimeout(timer);
});
});
});
function myFunction() {
console.log('Hello'); // note: use console.log to debug, especially with async/blocking functions
}
Upvotes: 2