0

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) 
            }
        }
3
  • Which variable gets undefined? Commented Apr 19, 2012 at 11:09
  • 3
    Never pass a string to setInterval() or setTimeout(). Doing so is as bad as using eval() 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 is setInterval(function() { /* your code *) }, msecs);. The same applies to setTimeout(). 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) Commented Apr 19, 2012 at 11:09
  • The url variable wich i use in the dotimer function first. Commented Apr 19, 2012 at 11:10

2 Answers 2

5
setTimeout("countredirect()",1000)

You are not passing any argument to your countredirect function.

Passing strings to setTimeout and setInterval is generally a bad idea (gives you all sorts of scope problems). Pass a function instead:

setTimeout(function() {
    countredirect(url);
}, 1000);

In newer browsers (or with shim) you can also use .bind() [MDN] (bind returns a new function):

setTimeout(countredirect.bind(null, url), 1000);
Sign up to request clarification or add additional context in comments.

Comments

0

An alternative approach to re-scheduling your function:

setTimeout(countredirect.bind(null, url), 1000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.