I made 3 versions of a counting-up timer in JavaScript:
Version #1
All units of time (seconds, minutes, hours, and days) are updated every second, whether they change or not.
Pro: Shorter code.
Con: Worse performance than version #2.
const timeIntervals = [
["day", 86400],
["hour", 3600],
["minute", 60],
["second", 1]
];
var counter = 1;
var tick = () => {
var gucci = counter;
for (unit of timeIntervals) {
$("#" + unit[0]).html(Math.floor(gucci / unit[1]));
gucci %= unit[1];
}
counter++;
};
var timer = window.setInterval(tick, 1000);
Version #2
Each unit of time (seconds, minutes, hours, and days) is updated only at fixed intervals when they change.
Pro: Better performance than version #1.
Con: Longer code.
const timeIntervals = [
["day", 86400],
["hour", 3600],
["minute", 60],
["second", 1]
];
var counter = 1;
var tick = () => {
let zero = false;
for (unit of timeIntervals) {
let element = $("#" + unit[0]);
if (zero) {
element.html("0");
}
else if (counter % unit[1] === 0) {
element.html(
parseInt(element.html()) + 1
);
zero = true;
}
}
counter++;
};
var timer = window.setInterval(tick, 1000);
Version #3
Each unit of time (seconds, minutes, hours, and days) is incremented up by 1 when the counter before it reaches its maximum limit.
Pro: Doesn't require a counter variable.
Con #1: It will break if the user clicks "Inspect Element" and messes with the HTML.
Con #2: Long code.
const timeIntervals = [
["second", 60],
["minute", 60],
["hour", 24],
["day", Infinity]
];
var tick = () => {
$("#second").html(
parseInt($("#second").html()) + 1
);
for (let i = 0; i < timeIntervals.length; i++) {
let currentElement = $("#" + timeIntervals[i][0]);
if (parseInt(currentElement.html()) >= timeIntervals[i][1]) {
currentElement.html("0");
let nextElement = $("#" + timeIntervals[i + 1][0]);
nextElement.html(parseInt(nextElement.html()) + 1);
}
}
};
var timer = window.setInterval(tick, 1000);
Which of these 3 codes has the best performance, readability, and structure? Do any of them have security vulnerabilities?