samedi 9 mai 2015

JavaScript: Variable undefined inside if else

Here I have a simple countdown function that redirects the user after 5 seconds.

<script type="text/javascript">

var timer = 5;
var counter = document.getElementById("countdown");

function countdown(target)
{
    counter.innerHTML = timer--;
    if (timer >= 0)
    {
        setTimeout(function () {
            countdown();
        }, 1000);
    }
    else
    {
        // Redirect the inactive user to the homepage

        console.log(target); // Outputs "undefined" after 5 seconds

        if (!typeof str === "undefined")
        {
            window.location.href = target;
        }
    }
};

var target = "/account/";
countdown(target);

</script>

The problem is, when 5 seconds elapse and it's time for the window.location.href to do the redirection, the "target" variable is undefined, I'm not sure why this happens.

I have researched and tried various solutions, even setting the "target" the way "timer" and "counter" are set, but none worked. My goal is to set a different "target" at each function instance.

Aucun commentaire:

Enregistrer un commentaire