Home >Web Front-end >JS Tutorial >【JavaScript】Countdown timer

【JavaScript】Countdown timer

高洛峰
高洛峰Original
2016-11-25 09:20:041187browse

1. Basic goal

Design a minute-to-second countdown timer in JavaScript. Once the time is completed, the button will become unclickable.

The specific effect is as shown below. In order to illustrate the problem, the table is adjusted to jump every 50 milliseconds, that is, every 0.05.

【JavaScript】Countdown timer

When actually using it, just adjust setInterval("clock.move()",50); in window.onload=function(){...} from 50 to 1000.

The button can still be clicked before time runs out.

After the time runs out, the button cannot be clicked.


2. Production process






time remaining



Remaining time:



<script><br/>/*The function to be used by the main function, declare it*/<br/>var clock=new clock(); <br/>/*Pointer to the timer*/<br/>var timer;<br/>window.onload=function(){<br/> /*The main function just calls the move method in the clock function every 50 seconds*/<br/> timer=setInterval ("clock.move()",50);<br/> }<br/>function clock(){<br/> /*s is a variable in clock(), not a global variable like var, which represents the remaining seconds*/<br/> this.s= 140;<br/> this.move=function(){<br/> /*Call the exchange function to convert seconds to minutes before output. Because exchange is not used in the main function window.onload, there is no need to declare it*/<br/> document.getElementById ("timer").innerHTML=exchange(this.s);<br/> /*Every time it is called, the remaining seconds will be decremented*/<br/> this.s=this.s-1;<br/> /*If the time runs out, Then, pop up the window, make the button unavailable, and stop calling move()*/<br/> in the clock function if(this.s<0){<br/> alert("Time is up");<br/> document.getElementById("go" ).disabled=true;<br/> clearTimeout(timer);<br/> }<br/> }<br/> }<br/>function exchange(time){<br/> /*Javascript’s division is floating point division, and Math.floor must be used to take the integer part*/<br/> this. m=Math.floor(time/60);<br/> /*There is a remainder operation*/<br/> this.s=(time%60);<br/> this.text=this.m+"minutes"+this.s+"seconds"; <br/> /*Do not use this for the formal parameter time passed, and other variables used in this function must use this*/<br/> return this.text;<br/>}<br/></script>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn