Reputation: 27
I need someone to tell me how to cancel or clear the timer on this function.
//Html
<a id="button" data-url="http://url.com">Click me!</a>
Redirecting in <span id="timer"></span> seconds...
<a href="javascript:void(0)" class="cancel">Cancel</a>
// jS
$('a#button').click(function() {
var url = $(this).attr("data-url");
if( url.indexOf("http://")!==0 ){
url = "http://"+url;
}
var seconds = 5,
el = $('#timer')
el.text(seconds)
setTimeout(function countdown() {
seconds--
el.text(seconds)
if (seconds > 0) {
setTimeout(countdown, 1000)
}
else {
window.open( url , "_self" )
}
}, 1000)
})
$('a.cancel').click(function(){
clearTimeout(countdown);
});
Also tell me what I"m doing wrong and why this isn't working.
Upvotes: 2
Views: 776
Reputation: 1056
I would do it like this : (edit: check it here http://jsfiddle.net/URHVd/3/ and it works fine)
var timer = null; //this will be used to store the timer object
var seconds = 5;
var url = null;
function countdown() {
seconds--;
el.text(seconds);
if (seconds > 0) {
timer = setTimeout(countdown, 1000)
}
else {
window.open( url , "_self" )
}
}
$('a#button').click(function() {
url = $(this).attr("data-url");
if( url.indexOf("http://")!==0 ){
url = "http://"+url;
}
el = $('#timer');
el.text(seconds)
timer = setTimeout(countdown, 1000)
})
$('a.cancel').click(function(){
clearTimeout(timer);
});
Upvotes: 1
Reputation: 1806
one way to do it nicely is:
{
var myTime;
myTime = setTimeout(function countdown() {
//blah
alert('Test');
clearTimeout(myTime);
}, 500);
}
then your variables are simply scoped.
Upvotes: 1
Reputation: 2654
You need to do this :
var myTime;
$('a#button').click(function() {
var url = $(this).attr("data-url");
if( url.indexOf("http://")!==0 ){
url = "http://"+url;
}
var seconds = 5,
el = $('#timer')
el.text(seconds)
myTime = setTimeout(function countdown() {
seconds--
el.text(seconds)
if (seconds > 0) {
myTime =setTimeout(countdown, 1000)
}
else {
//window.open( url , "_self" )
alert('no');
}
}, 500);
})
$('a.cancel').click(function(){
clearTimeout(myTime);
});
Upvotes: 4
Reputation: 15338
add:
var myTime;
myTime = setTimeout(function countdown() {...
to clear it do :
clearTimeout(myTime);
Upvotes: 3
Reputation: 382656
Tell setTimeout
what to cleaer:
countdown = setTimeout(function countdown() {...}
Make sure countdown
is declarted on top of script so that it is available inside click
handler.
Upvotes: 1