What about a magic function?
To talk about @Bradley Foster's answer, calling several times setTimeout
is not reliable. setTimeout
will stop if your browser lags, so with four differents, you're not sure the order is going to be the right one. Nesting the setTimeout
as I'm showing down there is better.
$('#button').click(function() {
var seconds = 5, // Declare some variables for reuse
el = $('#some_link')
el.text(seconds) // Put it a five!
// Name your function so that you can call it later
setTimeout(function countdown() {
// Your countdown is already at 5, so decrement it
// Remember that you've already waited for 1000ms before reaching this line the first time
seconds--
el.text(seconds) // Set the new time left
// If the countdown is not over, recall this function after 1000ms
if (seconds > 0) {
setTimeout(countdown, 1000)
}
// If it is over, display the link
// Note that js will stop there and not try to call itself another time as it would with setInterval()
else {
el.html('<a href="link">Download</a>')
}
}, 1000)
})
Btw, in your question, when you're doing $(function() {...
, you're actually doing $(document).ready(function() {...
. I guess this is not what you wanted :)
Jsfiddle here: http://jsfiddle.net/Ralt/kTbcm/