This article describes the implementation method of JavaScript minute and second countdown timer. Share it for your reference. The specific analysis is as follows:
1. Basic Objectives
Design a minute and second countdown timer in JavaScript, and once the time is completed, the button becomes unclickable.
The specific effect is as shown in the figure below. To illustrate the problem, it is adjusted to jump the table every 50 milliseconds, that is, every 0.05.
When you are actually using it, just adjust the setInterval("clock.move()",50); in window.onload=function(){...} from 50 to 1000.
The button can still be clicked before the time runs out.
After the time is used up, the button cannot be clicked.
2. Production process
Copy the code as follows:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>time remaining</title>
</head>
<!--html part is very simple. The line text and submit buttons that need to be controlled by javascript are all written with ID-->
<body>
Remaining time: <span id="timer"></span>
<input id="go" type="submit" value="go" />
</body>
</html>
<script>
/*The function to be used by the main function, declare it*/
var clock=new clock();
/*Pointer to the timer*/
var timer;
window.onload=function(){
/*The main function just calls the move method in the clock function once every 50 seconds*/
timer=setInterval("clock.move()",50);
}
function clock(){
/*s is a variable in clock(), a global variable that is not a var, representing the remaining seconds*/
this.s=140;
this.move=function(){
/*Before output, call the exchange function to convert from seconds to minute to second, because exchange is not used in the main function window.onload, so there is no need to declare it */
document.getElementById("timer").innerHTML=exchange(this.s);
/*Every time it is called, the remaining seconds will be reduced by itself*/
this.s=this.s-1;
/*If time runs out, then pop-up window makes the button unavailable, stop calling move() in the clock function*/
if(this.s<0){
alert("Time is up");
document.getElementById("go").disabled=true;
clearTimeout(timer);
}
}
}
function exchange(time){
/*Javascript's division is floating point division, and it must use Math.floor to take its integer part*/
this.m=Math.floor(time/60);
/*There is a residual operation*/
this.s=(time%60);
this.text=this.m+"minute"+this.s+"second";
/*Do not use this for the passed formal parameter time, while the remaining variables used in this function must use this*/
return this.text;
}
</script>
I hope this article will be helpful to everyone's JavaScript programming.