Feature-rich Countdown/Clock/Timer In Vanilla JavaScript – W3FClockTimer

Category: Date & Time , Javascript | February 4, 2020
Author: nrctkno
Views Total: 947 views
Official Page: Go to website
Last Update: February 4, 2020
License: MIT

Preview:

Feature-rich Countdown/Clock/Timer In Vanilla JavaScript – W3FClockTimer

Description:

W3FClockTimer is a feature-rich JavaScript to create countdown, clock, timer components on the app.

How to use it:

1. To get started, include the W3FClockTimer’s JavaScript and CSS on the page.

<link rel="stylesheet" href="src/w3fclocktimer.css" />
<script src="src/w3fclocktimer.js"></script>

2. Create a basic clock on the page.

<div id="clock">
  <span data-digit="h"></span>:<span data-digit="i"></span>:<span data-digit="s"></span>
  <span data-digit="m"></span>
  <span data-digit="H"></span> <span data-digit="a"></span>
  <span data-digit="d"></span>-<span data-digit="n"></span>-<span data-digit="y"></span>
  <span data-digit="w"></span>, <span data-digit="N"></span>
</div>
document.addEventListener("DOMContentLoaded", function (event) {
  document.getElementById('clock').W3FClockTimer();
});

3. Create a Pomodoro Timer with the W3FClockTimer plugin.

<div id="pomodoro-messages">Let's heat a soup. </div>
<div id="pomodoro" class="mystyle">
  <div class="mydate">
    <span data-digit="h"></span> <small>hours</small> <span data-digit="i"></span> <small>minutes</small>
  </div>
  <div class="mytime">
    <span data-digit="s"></span> <small>seconds</small>
  </div>
</div>
var pomodoro_msgs = document.getElementById('pomodoro-messages');

var pomodoro = document.getElementById('pomodoro').W3FClockTimer({
  device: {
    type: 'timer',
    //This is a helper to create a timestamp with an offset in seconds.
    //You can use a specific value written in ANSI format, e.g. '20190201 000000'
    deadline: W3FCT.fn.dt.stampFromOffset(20)
  },
  step: 100,
  //Milestones allow to fire an event only once, in a specific time.
  milestones: {
    //Milestone's value is device-dependant.
    //In case of 'timer', the value is a time span
    '00000000 000010': function (device, instant) {
      pomodoro_msgs.innerHTML += 'The soup is ready. ';
      pomodoro.classList.add("ok");
    },
    '00000000 000005': function (device, instant) {
      pomodoro_msgs.innerHTML += 'The soup is burning!! ';
      //if you don't want to assign an uoter var (e.g. "var pomodoro") you can access the target this way
      device.core.renderer.target.classList.add("danger");
    }
  },
  bind: {
    //Stop the device once the deadline is reached
    deadline: function (device) {
      device.core.stop();
      pomodoro_msgs.innerHTML += ' Pomodoro stopped.';
      device.core.renderer.target.classList.add("dead");
    }
  }
});

3. W3FClockTimer separates every instant in digits. This allows you to get or display every date component independently. A formatted value is returned by default. Appending the underscore (_), yo’ll get the numeric representation. For instance, when d returns "13", d_ returns 13.

Digit Description
y, y_ Year
n, n_ Month number (1 to 12)
d, d_ Day number (1 to 28, 29, 30 or 31)
h, h_ Hour, in 24-hour format
H, H_ Hour, in 12-hour format
a A.M. or P.M.
i, i_ Minutes (0 to 59)
s, s_ Seconds (0 to 59)
m, m_ Milliseconds (0 to 999)

4. W3FClockTimer provides some helpers to create timestamps. Those are very useful to create keys fro the milestone stack and deadlines for timers.

  • W3FCT.fn.dt.stamp(date): creates an ANSI representation for a Date object.
  • W3FCT.fn.dt.stampFromOffset(offset): creates a Date object given an offset in seconds and the current time.
  • W3FCT.fn.dt.fromANSI(ansi_string): converts an ANSI representation into a Date object.

5. Use milestones when you need to hook any behavior using an approximate time. Because of the relation between the step option and the accuracy level of any time object, W3Flints Clock-Timer cannot guarantee the punctual execution of a milestone, but it provides a second-to-second check, ensuring the execution of the milestone callback. The milestone queue is a key-value object, in which the key is a DateTime in ANSI format, and the value is a function that receives the device and the instant as parameters.

<div id="chrono-messages"> Ready.</div>
<div id="chrono" class="mystyle">
  <div class="myms">
    <span data-digit="h"></span>:<span data-digit="i"></span>:<span data-digit="s"></span>
    .<span data-digit="m"></span>
  </div>
</div>
var offset = 20;
var chrono_msgs = document.getElementById('chrono-messages');
var chrono_toggle = document.getElementById("chrono-start");

var chrono = document.getElementById('chrono').W3FClockTimer({
  //a timer
  device: {
    type: 'timer',
    ison: false,
    //we'll set up the deadline on start (see below)
    // deadline: W3FCT.fn.dt.stampFromOffset(offset) 
  },
  step: 10,
  milestones: {
    '00000000 000005': function (key, device) {
      chrono_msgs.innerHTML += ' Five seconds remaining.';
    },
    '00000000 000010': function (key, device) {
      chrono_msgs.innerHTML += ' Ten seconds remaining.';
    }
  },
  bind: {
    //fired when the instance is initialized
    init: function () {
      chrono_msgs.innerHTML += ' Ready.';
    },
    //fired when the core updates itself (based on "step" option)
    tick: function (key, device) {
      var i = device.getInstant();
      var color = 255 - (i.span * 0.001 / offset * 255);
      chrono.style.backgroundColor = 'rgba(' + color + ',200,200)';
    },
    //fired when the device is stopped
    stop: function (device) {
      chrono_msgs.innerHTML += ' Stopped.';
    },
    //fired when the instance in clicked
    click: function (device) {
      var d = device;

      var i = d.getInstant();
      chrono_msgs.innerHTML += ' Clicked at ' + i.h + ':' + i.i + ':' + i.s + ' ' + i.m + '.';

      if (d.core.isRunning()) {
        d.core.stop();
      } else {
        d.core.resume();
      }
    },
    //Timer only: fired when the difference between the deadline and the current time is zero
    deadline: function (device) {
      device.core.stop();
      chrono_msgs.innerHTML += ' Deadline reached.';
    }
  }
});

//Start the timer
chrono_toggle.addEventListener("click", function () {
  chrono.device.overrideDeadline(W3FCT.fn.dt.stampFromOffset(offset));//
  chrono.device.core.resume();
  chrono_msgs.innerHTML += ' Started.';
});

6. Full config options.

W3FClockTimer({

  //use it to localize your instances. See the Languages section
  lang: 'default',

  device: {
    //use 'clock' or 'timer'
    type: 'clock',
    //set it to off if you want to enable it manually
    ison: true, 
    //the offset, in seconds
    offset: 0
  },

  //the refresh speed, in milliseconds
  step: 100, 

  //see the Renderers section to get the full list
  renderer: {
    type: 'html',
    settings: {}
  },

  //use it to handle some time-dependant events. See the Milestones and bindings section
  milestones: {},

  bind: {
    //fired when the instance is initialized
    init: function () {},
    //fired when the core updates itself (based on step option)
    tick: function (key, device) {},
    //fired when the device is stopped
    stop: function (device) {}, 
    //fired when the instance in clicked
    click: function (device) {}, 
    //Timer only: fired when the difference between the deadline and the current time is zero
    deadline: function (device) {}
  }
  
});

7. Creating a new language is very simple. This can be achieved adding a new entry to the W3FCT.lang object.

W3FCT.lang.mySpanishLang = {
  days: ['DOM', 'LUN', 'MAR', 'MIE', 'JUE', 'VIE', 'SÁB'],
  months: ['ENE', 'FEB', 'MAR', 'ABR', 'MAY', 'JUN', 'JUL', 'AGO', 'SET', 'OCT', 'NOV', 'DIC'],
  ampm: ['a.m.', 'p.m.']
};

//set your previously created custom language
mytarget.W3FClockTimer({
  lang: 'mySpanishLang',
});

You Might Be Interested In:


Leave a Reply