Javascript timer writing process and implementation method, javascript Timer

Source: Internet
Author: User

Javascript timer writing process and implementation method, javascript Timer

JavaScript is a very easy-to-use scripting language. It has a wide variety of tools and powerful functions. Because it has always been related to the backend, I have just learned a little bit.

Next, go to the topic-timer. First, let's talk about the timer function:

1. The timer must be able to display the time on the page

2. The timer refresh every second. Every second is 60 minutes into 1 minute, and every minute is 60 minutes into 1 hour.

3. The timer needs to be reset, that is, re-timing

4. When the timer ends, you must be able to obtain the timer time.

The above functions are very simple. Timing should also have pause, continue timing and other functions. It doesn't matter. Let's do it one by one.

Step 1:

To create a simple page, we need to have a real-time tag with the start and pause buttons. The page is drawn as follows:

Don't spend too much time on a page. This is just to help you write your first code trainer ~

 Step 2:

Analyze the attributes required by the Timer:

1. Timing, Start Time Required

2. End Time

3. How long has this attribute been returned to the user?

4. The dashboard is actually a jquery object or dom object. Timing should be displayed in one place.

5. The display time needs to be disassembled, so we have the hour attribute.

6. Minute attribute

7. Second attribute (in fact, the total time is included. Remember it first. What if it is used)

Let's look at the Code:

Var startTime; // the start time var endTime; // The End Time var timeLength; // The total duration var timeSpan; // The time when the timer passes var displayer; // time display var hh = 0; // hour var mm = 0; // minute var status = 0; // time status

At first glance, it seems that there are several more attributes, because the timer will use the setTimeout method of JavaScript, and this method will return an object. We can use this object to clear setTimeout (clearTimeout );

 Step 3:

Let's analyze the timer methods:

1. The timer needs to be started, so we have a way to start it.

2. The timer needs to be stopped, so we have a stop method. After stopping the timer, we should tell the user how long it has been, so we should return the duration.

3. The timer should also have a pause function. After the pause, you can start timing again at the pause position. The pause duration should also be returned.

4. There should also be an inner activity of the timer every second around the start and stop, similar to a delegate method, which is executed once every second.

5. presentation logic. Let's talk about the real time display to the display device on the page, and make some readable and better format conversion.

On the code, constructor:

Function createTimer (_ startTime, _ endTime, _ timeLength, _ displayer) {startTime = _ startTime; // start time endTime = _ endTime; // End Time timeLength = _ timeLength; // total duration displayer = _ displayer; // time display hh = 0; // hour mm = 0; // minute status = 0; // timing status}

Timer start:

    var start =function(){      hh = 0;      mm = 0;      startTime=new Date();      status = setTimeout(beat, 1000);    } 

Timing ends:

    var stop=function(){      clearTimeout(status);      endTime=new Date();      timeLength=parseInt((endTime-startTime)/1000);      alert(timeLength);    }

Inner activity of the timer per second:

     var beat=function(){      endTime = new Date();      timeSpan = parseInt((endTime - startTime)/1000);      displayer[0].innerHTML = checkTime(timeSpan);      status = setTimeout(beat, 1000);    }

To display 00:00:00, we need a 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 to run ^_^

Is there something missing: How can a Timer not be paused? When I thought about it, I did not expect the pause function. I was watching it beat every second, so I was so happy until the business needed it, you have to add this feature.

It doesn't matter. Let's continue design. Add a pause button on the demo page: P

First, analyze:

1. after the pause, it must be restarted on the last paused node. This function is implemented in the Start button, so we need a flag to determine whether to start again or after the pause.

2. We need to record the pause time point

3. it is best to remember and use the pause interval. Otherwise, the time will jump to the interval immediately after the display starts again (for example, it is 00:00:09 at the pause time and one minute after the pause, if no adjustment is made, the start time will change to 00:01:09)

So we add three attributes:

Var isParse = false; // whether to suspend var parseTime; // The pause time point var intervalTime = 0; // The Interval

Pause method:

   var parse=function(){      parseTime = new Date();      isParse = true;      clearTimeout(status);    }  

Override the start method and rendering 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 the pause function ~

 

Check out the code. The core code contains less than one hundred lines.

Write it here, the main work is done, but it can also be encapsulated. With prototype, all methods are attached to an object. After instantiating a timer object and initializing some key attributes, these methods can be called by objects. I will not repeat it here. You can try it if you are interested ~

Articles you may be interested in:
  • VB countdown timer and current JS time
  • JS page timer sample code
  • Usage of javascript timer events
  • Detailed description of using timer to execute functions in Node. js
  • Implementation of the JavaScript minute-second countdown timer
  • JavaScript timer Example Analysis
  • Javascript timer details
  • Simple timer implemented by javascript
  • Simple stopwatch timer with javascript Design

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.