Search code examples
javascripttimernumbersincrementcountdown

Incrementing page number with JavaScript


I tried to figure out why the following code doesn't increment the page number, excepting from 1 to 2, but I couldn't find out.

<script>
var n = 1;
function increment() {
    return ++n; 
}
function countDown(secs,elem) {
    var element = document.getElementById(elem);
    element.innerHTML = "Timp rămas: "+secs+" secunde.";
    if(secs < 1) {
        clearTimeout(timer);
        window.location.replace('question.php?n='+increment(n));
        element.innerHTML += '<a href="#">Click here now</a>';
    }
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>

Ideas?


Solution

  • Try this:

    var params = new URL(document.location).searchParams;
    var n = params ? params.get('n') || 1 : 1; 
    

    So n is read from URL and not set to 1 everytime a page is loaded.

    Edit: ah, and maybe:

    var timer = setTimeout(function(){countDown(secs, elem);},1000);