Timers are also frequently used functions in life, such as exercise, running competitions and other related activities. We use Javascript to complete a timer.
Timer is mainly a logical processing of time. For example, 60 seconds is equal to 1 minute, and 60 minutes is equal to one hour. We only deal with hours here. It is such a simple logic, and then dynamically displayed in a Inside Input.
Now let’s complete this interface
<label>计时:</label> <input type="text" name="" id="timer"/> <button onclick="pause(this)" id="pause" state="on">暂停</button> <button onclick="restart()">重新开始</button>
The purpose of giving the label element an ID is to obtain the label, and then adding two click events, a pause event for the counter, and a restart event.
First of all, let’s complete the process of starting timing. To start timing, we mainly use the setInterval method, which executes the method every 1 second, so that we can process the time. As mentioned at the beginning, 60 seconds is equal to 1 Minutes..., so you need to use judgment to process it, and finally display the obtained seconds, minutes, and hours into the input box.
var ele_timer = document.getElementById("timer"); var n_sec = 0; //秒 var n_min = 0; //分 var n_hour = 0; //时 //60秒 === 1分 //60分 === 1小时 function timer() { return setInterval(function () { var str_sec = n_sec; var str_min = n_min; var str_hour = n_hour; if ( n_sec < 10) { str_sec = "0" + n_sec; } if ( n_min < 10 ) { str_min = "0" + n_min; } if ( n_hour < 10 ) { str_hour = "0" + n_hour; } var time = str_hour + ":" + str_min + ":" + str_sec; ele_timer.value = time; n_sec++; if (n_sec > 59){ n_sec = 0; n_min++; } if (n_min > 59) { n_sec = 0; n_hour++; } }, 1000); } var n_timer = timer();
We use the timer method to wrap the setInterval method in order to pause and restart processing later.
When the user clicks pause, the timer will stop timing. If the user continues to click the button, the timer will continue timing. So there is a state that needs to be controlled. For this state, we give the button an attribute.
//暂停和继续 function pause(self) { var state = self.getAttribute("state"); if (state === "on") { clearInterval(n_timer); self.textContent = "继续"; self.setAttribute("state", "off"); } else { n_timer = timer(); self.textContent = "暂停"; self.setAttribute("state", "on"); } }
Finally let’s take a look at restarting. Restarting the event is even simpler. Clear the counter to 0, and then change the initial state of the pause button.
function restart() { clearInterval(n_timer); n_sec = 0; n_min = 0; n_hour = 0; n_timer = timer(); var ele_pause = document.getElementById("pause"); ele_pause.textContent = "暂停"; ele_pause.setAttribute("state", "on"); }
This completes the timing function. The effect is as follows
I hope this article will be helpful to everyone in learning javascript programming.