


JavaScript timer writing process and implementation method_javascript skills
JavaScript is a very easy-to-use scripting language with many tools and powerful functions. Because I have been working on the back-end, I have only scratched the surface.
Then let’s get to the main topic – timer. Let’s talk about the function of the timer first:
1. The timer must be able to display the time on the page
2. The timer is refreshed every second. Every time the second reaches 60, the minute advances by 1, and when the minute reaches 60, it advances by 1 hour.
3. The timer needs to be able to be reset, that is, to retime
4. When the timer ends, there needs to be a way to get the timer
The above functions are very simple. The timing should also have functions such as pausing, continuing timing, etc. It doesn’t matter, we will do it one by one.
Step one:
We make a simple page with a real time label and start and pause buttons. The page is drawn as follows:
Don’t spend too much time on one page, this is just to help you practice writing the first piece of code~
Step 2:
Let’s analyze what attributes the timer needs:
1. Timing, start time is required
2.End time
3. The total walking time, this attribute is to be returned to the user
4. The displayer is actually a jquery object or dom object. The timing needs to be displayed in one place
5. The display time needs to be dismantled, so we have the hour attribute
6. Minute attribute
7. Second attribute (actually included in the total time, write it down first in case you need it)
Let’s take a look at the code:
var startTime;//开始时间 var endTime;//结束时间 var timeLength;//总时长 var timeSpan;//计时器走过的时间 var displayer;//时间显示器 var hh=0;//小时 var mm=0;//分钟 var status=0;//计时状态
At first glance, it seems that there are a few more attributes, because timing uses the JavaScript setTimeout method, which returns an object. We can use this object to clear setTimeout (clearTimeout);
Step 3:
Let’s analyze what methods are needed for timers:
1. The timer needs to be started, so we have a method to start
2. The timer needs to be stopped, so we have a stop method. After stopping, it should tell the user how long it has counted, so the time should be returned
3. The timer should also have a pause function. After pausing, you can start timing again at the paused position, and the pause should also return to the duration
4. Around starting and stopping, there should also be inner activities of a timer every second, similar to a delegate method, executed once every second
5. Presentation logic, we need to display the real time to the presenter on the page, and do some format conversions for better readability
Above code, constructor:
function createTimer(_startTime,_endTime,_timeLength,_displayer){ startTime=_startTime;//开始时间 endTime=_endTime;//结束时间 timeLength=_timeLength;//总时长 displayer=_displayer;//时间显示器 hh=0;//小时 mm=0;//分钟 status=0;//计时状态 }
Timer starts:
var start =function(){ hh = 0; mm = 0; startTime=new Date(); status = setTimeout(beat, 1000); }
Timeout ends:
var stop=function(){ clearTimeout(status); endTime=new Date(); timeLength=parseInt((endTime-startTime)/1000); alert(timeLength); }
Inner activity of timer per second:
var beat=function(){ endTime = new Date(); timeSpan = parseInt((endTime - startTime)/1000); displayer[0].innerHTML = checkTime(timeSpan); status = setTimeout(beat, 1000); }
In order to display 00:00:00 in the above picture, we need a piece of presentation logic
var checkTime=function(len){ len=len-mm*60; if (len >= 60) { this.mm++; //starttime1 = new Date(); len = 0; } mm=mm-hh*60; if (mm >= 60) { hh++; mm = 0; } return j(self.hh) + ":" +j(mm) + ":" + j(len); } var j=function(arg){ return arg >= 10 ? arg : "0" + arg; }
We start the timer and this simple timer starts running^_^
Is there something missing? How can the timer not be paused? When I conceived these ideas, I didn’t expect the pause function. I was watching it jump second by second. I was so happy until the business needed it. , then I remembered that I need to add this function.
It doesn’t matter, let’s continue designing and add a pause button on the demo page:P
Let’s analyze it first:
1. After pausing, you must restart on the last paused node. We implement this function in the start button, so we need a flag to determine whether to restart or start after pause
2. We need to record the time point of the pause
3. It is best to write down the pause time interval so that it can be used, otherwise when you start again, the time will immediately jump to after the interval in the presentation (for example, when you pause, it is 00:00:09, and you pause for one minute Afterwards, if you start directly without making adjustments, the time will become 00:01:09)
So we add three attributes:
var isParse=false;//是否为暂停 var parseTime;//暂停时间点 var intervalTime = 0;//暂停时间间隔
Pause method:
var parse=function(){ parseTime = new Date(); isParse = true; clearTimeout(status); }
Override the start method and render method:
var start =function(){ if(!isParse){ startTime=new Date(); startTime1=startTime; hh = 0; mm = 0; startTime=new Date(); status = setTimeout(beat, 1000); } else{ intervalTime=parseInt((intervalTime + (new Date() - parseTime) / 1000)); starttime1 = startTime; status = setTimeout(beat, 1000); } } var checkTime=function(len){ len=len-mm*60-intervalTime; if (len >= 60) { mm++; len = 0; } mm=mm-hh*60; if (mm >= 60) { hh++; mm = 0; } return j(hh) + ":" +j(mm) + ":" + j(len); }
The above is done, our timer has a pause function~
Look at the overall code overview, the core code is less than a hundred lines.
Having written this, the main work is done. In fact, you can also encapsulate and use prototype to attach all the methods to an object. After instantiating a timer object and initializing some key attributes, these methods can be Object call. I won’t go into details here. If you are interested in children’s shoes, you can try them~

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

To use built-in Pomodoro technology in Windows 11 or Windows 10, you can set a timer through the built-in Clock app. This can help you use your time more effectively and improve work efficiency. Using Pomodoro technology allows you to focus on completing tasks in a short period of time and avoid distractions and procrastination. The built-in clock app provides convenient timing and reminder functions to help you work according to the Pomodoro technology work cycle. By setting working hours and break times, you can better manage your time and increase work efficiency. Therefore, using the built-in tools provided by the Windows system to practice Pomodoro technology can help you complete your work tasks more efficiently. Po

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
