Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

web - How can I do a countdown timer with html?

I'm helping my I.T teacher to create easter eggs for some tasks, and I would like to create a countdown timer with html. Explanation: Everytime you enter into a website, the countdown timer starts. Example: I have a html code with a countdown timer at 30 min, if I go into the website, the countdown timer starts going down, but if I refresh the website, it reset. I hope you will understand, thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to use only javascript, without any server-side language you could store the time that is left in the localStorage variable, because after you exit the website/browser it will stay the same;

Example:

function countdown() {
    time = parseInt(localStorage.time); //All variables in localstorage are strings
    //Resets timer if cannot parse the localStorage.time variable or if the time is greater than 30 mins
    if(isNaN(time) || time > (30*60)) {
        alert("An error occured: time left variable is corrupted, resetting timer");
        localStorage.time = 30*60; //30 mins in seconds
        countdown();
        return null;    
    }
    //Decrementing time and recalling the function in 1 second
    time--;
    localStorage.time = time;
    setTimeout('countdown()', 1000);
}

You can add a function that turn seconds into: Minutes:Seconds and edit the function so it will change an element everytime it calls it self, or do something when the time reaches 0(don't forget to call it once, unless the timer won't run). Good luck!

I made a pen for you: http://codepen.io/DaCurse0/pen/kkxVYP

It should have everything you need.

P.S: you should probably remove the alert when checking if timer is corrupted because it will show when the timer wasn't set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...