For an exercise, I created a simple function to display a "binary clock" that updates every two seconds instead of one. This function is actually a modified version of similar code that works within an HTML form (updating a value repeatedly).
Below is my JavaScript-only modification:
function binaryClock() {
let currentTime = new Date();
let hr = currentTime.getHours();
let mn = currentTime.getMinutes();
let sc = currentTime.getSeconds();
setTimeout('binaryClock()', 2000);
document.body.innerHTML = '';
document.write(hr + ':' + mn + ':' + sc + ' ');
}
binaryClock();
Why does it operate in intervals like a regular clock where setTimeout
essentially acts as setInterval
with the binaryClock callback?
I find it intriguing that using setInterval()
yields the same outcome, and as a beginner, I lack the necessary knowledge to explain why setTimeout()
, typically executed once, mimics setInterval()
behavior in this scenario. This discrepancy has piqued my interest enough to inquire about it here since I have not encountered such variance in my learning.