I have a countdown script that redirects to a file. It has a loop in it and the variable gets undifined when it ran once.
How can i keep the url variable to hold its value?
<a id="" onClick="doTimer('http://www.domain.com/downloadfile.php?photo=foo.jpg')" href="#"><button id="download">Download this photo</button></a>
var timer_is_on=0;
var countdownfrom=5
var currentsecond=document.getElementById('countdown').innerHTML=countdownfrom+1
function countredirect(url)
{
if (currentsecond!=1)
{
currentsecond-=1
document.getElementById('countdown').innerHTML = currentsecond;
}
else
{
window.location=url
return
}
setTimeout("countredirect()",1000)
}
function doTimer(url)
{
if(!timer_is_on)
{
document.getElementById('download').innerHTML="Your download starts in <span id=\"countdown\"></span>seconds";
timer_is_on=1;
countredirect(url)
}
}
setInterval()orsetTimeout(). Doing so is as bad as usingeval()and it results in unreadable and possibly insecure code as soon as you use variables since you need to insert them into the string instead of passing the actual variable. The proper solution issetInterval(function() { /* your code *) }, msecs);. The same applies tosetTimeout(). If you just want to call a single function without any arguments, you can also pass the function name directly:setInterval(someFunction, msecs);(note that there are no()behind the function name)