Here is the code for the countdown timer that displays on this site on Switch consoles!
It uses the localStorage property of the browser to store the start time and date when the page is first visited. This occurs right after the DNS connects, when using browseDNS. Then it calculates the difference between the current time and the start time, subtracts that from 20 minutes, then displays it.
function startTimer() {
// check if a start time has been previously noted
if (window.localStorage.getItem('startTime') == null) {
// Local storage isn't persisted between sessions, so if we don't have
// a start time, we're likely in a new session. Set the start time to now.
window.localStorage.setItem('startTime', new Date().getTime());
}
// grab that start time
var startTime = window.localStorage.getItem('startTime');
// and the current time
var presentTime = new Date().getTime()
// calculate the difference between the two, and that's how long our session has been
var diff = presentTime - startTime;
// 20 minutes is 1200000 milliseconds (20 * 60 * 1000)
var maxSessionLength = 1200000;
// subtract the time difference from the max session length to get the remaining time
var timeRemaining = maxSessionLength - diff;
// if the remaining time is negative, just set it to 0
if (timeRemaining < 0) {
timeRemaining = 0;
}
// convert the remaining time to minutes and seconds
var minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);
// update the display span with the remaining time, and pad the seconds with a 0 if needed
document.getElementById("timer").innerHTML = minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}
// run the timer logic once, and then repeat every second (1000 ms)
startTimer();
setInterval(startTimer, 1000);
This function runs every 1000ms (that's what setInterval does). When it hits 0, nothing actually happens, but after the browser does time out, the localStorage info is wiped, and the countdown will start fresh on the next launch.
Since it uses the wall time, this will persist across other sites on the Internet upon returning to browsedns. However, this also means it will become inaccurate when sleeping the console, leaving, and returning, which does not tick down Nintendo's counter.