It is important to note that relying on this method for high security is not recommended, as the source code can be easily read and the link deciphered. Even with obfuscation, determined individuals can still decode it if the browser is capable of doing so.
var twentyMins = 20 * 60; // Calculating 20 minutes in seconds
window.onload = function() {
countDown('my_div1', '<a href="cdtl.html">Hello 1</a>', twentyMins);
}
function countDown(elID, output, seconds) {
var mins,
secs = seconds,
pad = function (n) {
return n > 9 ? n : '0' + n;
};
hours = Math.floor(secs / 3600);
secs %= 3600;
mins = Math.floor(secs / 60);
secs %= 60;
secs = pad(secs);
mins = pad(mins);
hours = pad(hours);
document.getElementById(elID).innerHTML = (seconds === 0) ? output : 'Time until link appears: ' + hours + ':' + mins + ':' + secs;
if (seconds !== 0) {
seconds -= 1;
setTimeout(countDown, 1000, elID, output, seconds);
}
}
View jsFiddle demo here
Instead, using setInterval
rather than setTimeout
would be a more reliable approach. Timers are unpredictable due to varying delays, which can affect the execution timing. Using setInterval
allows for consistent updates without potential disruptions caused by alerts or background processes.
The modern environment of browsers may also impact timer accuracy, making timer resolutions fluctuate. Implementing setInterval
mitigates these issues and ensures smoother countdown functionality.
var twentyMins = 20 * 60;
window.onload = function() {
countDown('my_div1', '<a href="cdtl.html">Hello 1</a>', twentyMins);
}
function countDown(elID, output, seconds) {
"use strict";
var timer,
el = document.getElementById(elID),
getTime = function () {
return (new Date()).getTime();
},
finishAt = getTime() + (seconds * 1000),
pad = function (n) {
return n > 9 ? n : '0' + n;
},
lastCount = -1,
update = function () {
var hours,
now = getTime(),
mins,
secs = Math.floor((finishAt - now) / 1000);
if (lastCount !== secs) {
lastCount = secs;
if (now >= finishAt) {
clearInterval(timer);
el.innerHTML = output;
} else {
hours = Math.floor(secs / 3600);
secs %= 3600;
mins = Math.floor(secs / 60);
secs %= 60;
secs = Math.floor(secs);
secs = pad(secs);
mins = pad(mins);
hours = pad(hours);
el.innerHTML = 'Time until link appears: ' + hours + ':' + mins + ':' + secs;
}
}
};
update();
timer = setInterval(update, 499);
}
Check out the updated version on jsFiddle
In both solutions provided, the remainder operator was used for calculating time components due to its efficiency compared to alternative methods. Additionally, employing strict equality operators enhances performance and conforms to coding best practices.
Enhanced features in the improved solution include storing previous counts to minimize redundant calculations and DOM accesses. Utilizing setInterval
optimizes the countdown process and reduces inaccuracies stemming from browser nuances.