Home > Mobile >  How to make countdown start after clicking a button using local storage
How to make countdown start after clicking a button using local storage

Time:03-20

if(localStorage.getItem("total_seconds")){
    var total_seconds = localStorage.getItem("total_seconds");
} 
else {
        var total_seconds = 6*10;
} 
var minutes = parseInt(total_seconds/60);
var seconds = parseInt(total_seconds`);

function countDownTimer(){
    if(seconds < 10){
        seconds= "0"  seconds ;
    }
    if(minutes < 10){
        minutes= "0"  minutes ;
} 
document.getElementById("quiz-time-left").innerHTML = "Time Left :" minutes "minutes" seconds "seconds";
    if(total_seconds <= 0){
        setTimeout("document.quiz.submit()",1);
        
    } else {
        total_seconds = total_seconds -1 ;
        minutes = parseInt(total_seconds/60);
        seconds = parseInt(total_seconds`);
        localStorage.setItem("total_seconds",total_seconds)
        setTimeout("countDownTimer()",1000);
} 
} 
setTimeout("countDownTimer()",1000);

Here is the countdown code I copied, I want this counter to start after button is clicked but I can't seem to succed I couldn't find a way to put the onclick working function would be good if I could receive some suggestions and tips

CodePudding user response:

put your last line setTimeout(countDownTimer(),1000); inside a function of an onclick event; If you've specified `onclick' as an attribute in the html of the button, it's value should be set to the name of the function you've put it inside:

<button onclick="startTimer();">start</button>

where your js has

function startTimer (){
  setTimeout(countDownTimer,1000);
}

alternatively, put setTimeout(countDownTimer,1000); inside an event listener for the button:

let buttonElement = document.getElementById(<id attribute of button>);

buttonElement.addEventListener('click', () {setTimeout(countDownTimer,1000)});

Also, get rid of the quotes around countDownTimer() - it is a function, not a string. The function name inside setTimeout should not have (), just the function name. Lastly, setTimeout will trigger once, after the time argument. If you need it to run every 1000 ms, use setInterval instead.

To resume the timer automatically when the user returns, modify the initial if block as follows:

if(localStorage.getItem("total_seconds")){
    var total_seconds = localStorage.getItem("total_seconds");
    // start timer from here as storage was found;
    startTimer ();
} 
else {
        var total_seconds = 6*10;
} 

That way, a call is made to start the timer if a value was found in storage, indicating a previous visit. You might want to include some check on what the value is uncase it already reached zero, but the rest of your code may take care of that anyway.

  • Related