How can I automatically "click" a button when a timer counts down to "0"? (How do I call click on a button from code?)

5.7k views Asked by At

I am preparing an exam page. I have a time counter and it counts back from 60 seconds down to 0. There is a button NEXT, I want to skip to the next question when the time ends for the question. When you select your answer through the radio buttons and click NEXT, the page redirects to the next question, but when the time is up, I want the BUTTON be clicked automatically in order to skip to the next question.

Here is my code for counter :

function startResetTimer() {

    time = 60;
    interval = setInterval(function() {
        time--;
        document.getElementById('Label1').innerHTML = "" + time + " seconds"
    }, 1000)
}

The remaining time is shown on the label label1 and the name of my button is SubmitButton.

1

There are 1 answers

3
DDan On BEST ANSWER
interval = setInterval(function() {
    time--;
    document.getElementById('Label1').innerHTML = "" + time + " seconds"
    if (time == 0) {
        // stop timer
        clearInterval(interval);
        // click
        document.getElementById('thebutton').click();            
    }
}, 1000)

Here is a JSFiddle: https://jsfiddle.net/ddan/cmtqzwa7/