JavaScript timer writing process and implementation method _javascript skills

Source: Internet
Author: User
Tags javascript settimeout

JavaScript is a very easy to start scripting language, but also a wide range of tools, powerful, because always do the back-end relationship, the author is currently just a little bit of fur.

Let's get to the point--the timer. Let's talk about the function of the timer:

1. Timer to be able to display time on the page

2. Timer refresh per second, seconds per full 60 Minutes 1, minutes every 60 into the hour 1

3. Timers need to be able to reset, that is, to reset the clock

4. At the end of the time, you need to have access to the timing of the method

The above function is very simple, the timing should also have pause, continue to time and other functions, it does not matter, we are one to come.

First step:

We do a simple page, to have a realistic time tag, to have a start, pause two buttons, the page is drawn as follows:

Don't spend too much time on a page oh, it's just to help you write the first piece of code to practice practicing ~

Step Two:

We analyze what attributes are required for the timer:

1. Timing, need to start time

2. End time

3. How long has it been gone, this property is to be returned to the user

4. The display, in fact, is a jquery object or DOM object, the timing is to be shown in a place

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

6. Minute attributes

7. Second attribute (in fact, the total time is included, first remember, in case you can use it)

Let's look at the code:

    var starttime;//start time var
    endtime;//end time var
    timelength;//total time long
    var timespan;//timer traversed the time
    var displayer ;//time display
    var hh=0;//hour var
    mm=0;//minute
    var status=0;//timing Status  

At first glance there seems to be a few more attributes, because the timings use the JavaScript settimeout method, which returns an object that we can use to erase settimeout (cleartimeout);

Step Three:

We analyze what is needed for the timer:

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

2. The timer needs to stop, so we have the Stop method, should tell the user how long after the stop, so should return the length of time

3. The timer should also have a pause function, after a pause, you can start the time in the position of pause again, pause should also return the length

4. Around the start stop, there should also be a timer every second of the inner activity, similar to a delegate method, the United States second execution

5. Rendering logic, we need to talk about real time display to the display on the page, and do some more readable format conversion

On the code, constructor:

function Createtimer (_starttime,_endtime,_timelength,_displayer) {
      starttime=_starttime;//start time
      endTime=_ endtime;//End time
      timelength=_timelength;//total time
      displayer=_displayer;//time display
      hh=0;//hours
      mm=0;//minutes
      status=0;//timing Status
    }  

Timer start:

    var start =function () {
      hh = 0;
      MM = 0;
      Starttime=new Date ();
      Status = SetTimeout (beat, 1000);
    

Timer End:

    var stop=function () {
      cleartimeout (status);
      Endtime=new Date ();
      Timelength=parseint ((endtime-starttime)/1000);
      alert (timelength);
    }

The 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);
    }

In order to be able to show the 00:00:00 of the above, we need a presentation logic

  var checktime=function (len) {
      len=len-mm*60;
      if (len >=) {
        this.mm++;
        starttime1 = new Date ();
        len = 0;
      }
      mm=mm-hh*60;
      if (mm >=) {
        hh++;
        MM = 0;
      }
      Return J (SELF.HH) + ":" +j (mm) + ":" + j (len);
    }
  
    var j=function (Arg) {return
      arg >= arg: "0" + arg;
    } 

We start the timer, and this simple timer starts running. ^_^

is not what is missing: The timer can not be paused ah, the author that will conceive these time, also did not think of suspend function, is watching it a second beat, silly music, until the business needs, just remember, have to add this function.

Okay, let's continue with the design, add a pause button on the demo page: P

First analysis of the following:

1. After the pause, be sure to restart on the last paused node, this piece of functionality we do in the Start button, so we need a bit to determine whether to start again, or pause after the start

2. We need to record the pause time.

3. Pause interval Best can also be recorded, can be used to get, otherwise start again, time in the rendering will immediately jump to the interval after (for example, pause is 00:00:09, pause a minute, if not make adjustments directly start, time will become 00:01:09)

So we added three attributes:

  Whether Var isparse=false;//is paused
    var parsetime;//pause point-in-time
    var intervaltime = 0;//Pause interval

Pause Method:

   var parse=function () {
      parsetime = new Date ();
      Isparse = true;
      Cleartimeout (status);
      

To 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 >=) {
        mm++;
        len = 0;
      }
      
      mm=mm-hh*60;
      if (mm >=) {
        hh++;
        MM = 0;
      }
      Return J (HH) + ":" +j (mm) + ":" + j (len);
    }  

Above, done, our timer has a pause function ~

Look at the entire code, less than 100 lines of core code.

Write here, the main work is done, in fact, can also be encapsulated, using prototype, the method is all attached to an object, when instantiating a timer object and initialize some key properties, these methods can be invoked by the object. Here is not to repeat, interested in children's shoes can try ~

Related Article

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.