Reputation: 97
I'm trying to make a dynamic function that makes redirects but it doesn't work It returns me 'undefined'
here is the HTML code:
<p>You will be redirected to the page X in <span id="time">4</span> seconds..</p>
here is the JavaScript code:
var seconds;
var temp;
function countdown(page) {
seconds = document.getElementById('time').innerHTML;
seconds = parseInt(seconds, 10);
if (seconds == 1) {
temp = document.getElementById('time');
temp.innerHTML = '0. If you are not, please click <a href="' + page + '">here</a>.';
window.location = page;
return;
}
seconds--;
temp = document.getElementById('time');
temp.innerHTML = seconds;
timeoutMyOswego = setTimeout(countdown, 1000);
}
countdown('/asimplepage/asdfgh.html');
I tried also to do:
function redirect(page){
window.location = page;
}
redirect('thisworks.html');
Upvotes: 0
Views: 398
Reputation: 65806
The problem is with this line:
timeoutMyOswego = setTimeout(countdown, 1000);
When setTimeout
invokes countdown
, it is not passing the page
parameter that originally kicks the function off. So, the second (and subsequent times) that countdown
runs, nothing is being passed in for page
.
Change the line to:
timeoutMyOswego = setTimeout(function(){countdown(page)}, 1000);
This instructs the setTimeout()
function to schedule a call to the anonymous function, which in turn will call countdown
and supply countdown
with the page
variable value, after one second.
Upvotes: 1