HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Timer in pure JavaScript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascripttimerpure

Problem

I was working on a timer code in pure JavaScript and would like to know any pointers to improve:

Features

  • Start/ Stop/ Reset on click of a button.



  • Set limit to clock.



  • Update class name for warning and error based on threshold timer.



JSFiddle



`function timer() {
var time = {
sec: 00,
min: 00,
hr: 00
};
var finalLimit = null,
warnLimit = null,
errorLimit = null;
var max = 59;
var interval = null;

function init(_hr, _min, _sec) {
time["hr"] = _hr ? _hr : 0;
time["min"] = _min ? _min : 0;
time["sec"] = _sec ? _sec : 0;
printAll();
}

function setLimit(fLimit, wLimit, eLimit) {
finalLimit = fLimit;
warnLimit = wLimit;
errorLimit = eLimit;
}

function printAll() {
print("sec");
print("min");
print("hr");
}

function update(str) {
time[str] ++;
time[str] = time[str] % 60;
if (time[str] == 0) {
str == "sec" ? update("min") : update("hr");
}
print(str);
}

function print(str) {
var _time = time[str].toString().length == 1 ? "0" + time[str] : time[str];
document.getElementById("lbl" + str).innerHTML = _time;
}

function validateTimer() {
var className = "";
var secs = time.sec + (time.min 60) + (time.hr 60 * 60);
if (secs >= finalLimit) {
stopTimer();
} else if (secs >= errorLimit) {
className = "error";
} else if (secs >= warnLimit) {
className = "warn";
}
var element = document.getElementsByTagName("span");
document.getElementById("lblsec").className = className;
}

function startTimer() {
init();
if (interval) stopTimer();
interval = setInterval(function() {
update("sec");
validateTimer();
}, 1000);
}

function stopTimer() {
window.clearInterval(interval);
}

function resetInterval() {
stopTimer();
time["sec"] = time["min"] = time["hr"] = 0;
printAll();
startTimer();
}

return {
'start': startTimer,
'stop': s

Solution

It looks really good! Here are a few points;

I don't like the arguments in your setLimit and init functions, especially because some of them are optional.

I would prefer an Object argument in this case.

function setLimit(limits) {
  finalLimit = limits.final;
  warnLimit = limits.warn;
  errorLimit = limits.error;
}

this.setLimit({
  final: 10,
  warn: 5,
  error: 8
});


This makes it obvious at call time which argument is which.

Your var declarations are inconsistent here:

var finalLimit = null,
  warnLimit = null,
  errorLimit = null;
var max = 59;
var interval = null;


Pick either to comma separate them or not. Not both.

In a couple of places you use == instead of ===. Generally we stick to === for reasons.

You CSS selectors are very generic. This is generally a bad thing as they will easily collide with other styles the moment you integrate it into a real page.

I favour BEM syntax, which would make it look something like this;


   
      00
    : 00
    : 00

  
  Start
  Stop
  Reset


Note I've also removed your onclick handlers in favour of interaction specific classes. I prefix my classnames with js- if they are used solely for JavaScript selectors. This helps decouple the CSS and JavaScript.

In your code you then attach the handlers;

document.querySelectorAll('.js-start-timer')[0]
  .addEventListener('click', startTimer);

Code Snippets

function setLimit(limits) {
  finalLimit = limits.final;
  warnLimit = limits.warn;
  errorLimit = limits.error;
}


this.setLimit({
  final: 10,
  warn: 5,
  error: 8
});
var finalLimit = null,
  warnLimit = null,
  errorLimit = null;
var max = 59;
var interval = null;
<div class="timer">
  <div class="timer__labels"> 
      <span id="timer__hours-label">00</span>
    : <span id="timer__minutes-label">00</span>
    : <span id="timer__seconds-label">00</span>

  </div>
  <button class="timer__btn js-start-timer">Start</button>
  <button class="timer__btn js-end-timer">Stop</button>
  <button class="timer__btn js-reset-timer">Reset</button>
</div>
document.querySelectorAll('.js-start-timer')[0]
  .addEventListener('click', startTimer);

Context

StackExchange Code Review Q#111802, answer score: 2

Revisions (0)

No revisions yet.