MediaWiki:Gadget-countdown-timer.js: Difference between revisions

From IdleOn MMO Wiki
(Created page with "→‎jshint esversion: 6: $(() => { const timers = [] class CountdownTimer { constructor($elem) { this.$elem = $elem; // TODO Query the element for the expiration time. this.expiration = Date.now() + (90 * 1000); } tick() { const time = Math.floor((this.expiration - Date.now()) / 1000); const s = time % 60; const m = Math.floor(time / 60) % 60; const h = Math.floor(time / 3600) % 24; const d = Math.floor(time / 86400); l...")
 
No edit summary
Line 3: Line 3:
$(() => {
$(() => {
const timers = []
let timers = [];
class CountdownTimer {
class CountdownTimer {
Line 20: Line 20:
const d = Math.floor(time / 86400);
const d = Math.floor(time / 86400);
let text = ''
let text = '';
let showUnit = d > 0;
let showUnit = d > 0;
Line 29: Line 29:
showUnit |= h > 0;
showUnit |= h > 0;
if (showUnit) {
if (showUnit) {
text += h + 'h'
text += h + 'h';
}
}
Line 50: Line 50:
function tick() {
function tick() {
// Tick and automatically remove expired timers.
// Tick and automatically remove expired timers.
timers = timers.filter(t => t.tick())
timers = timers.filter(t => t.tick());
if (timers.length != 0) {
if (timers.length != 0) {
setTimeout(tick, 1000)
setTimeout(tick, 1000);
}
}
}
}
Line 65: Line 65:
.addClass('managed')
.addClass('managed')
.each(() => {
.each(() => {
const timer = new CountdownTimer($(this))
const timer = new CountdownTimer($(this));
timers.push(timer)
timers.push(timer);
});
});

Revision as of 05:35, 22 May 2024

/* jshint esversion: 6 */

$(() => {
	
	let timers = [];
	
	class CountdownTimer {
		constructor($elem) {
			this.$elem = $elem;
			// TODO Query the element for the expiration time.
			this.expiration = Date.now() + (90 * 1000);
		}
		
		tick() {
			const time = Math.floor((this.expiration - Date.now()) / 1000);
			
			const s = time % 60;
			const m = Math.floor(time / 60) % 60;
			const h = Math.floor(time / 3600) % 24;
			const d = Math.floor(time / 86400);
			
			let text = '';
			
			let showUnit = d > 0;
			if (showUnit) {
				text += d + 'd';
			}
			
			showUnit |= h > 0;
			if (showUnit) {
				text += h + 'h';
			}
			
			showUnit |= m > 0;
			if (showUnit) {
				text += m + 'm';
			}
			
			showUnit |= s > 0;
			if (showUnit) {
				text += s + 's';
			}
			
			$elem.text(text);
			
			return time > 0;
		}
	}
	
	function tick() {
		// Tick and automatically remove expired timers.
		timers = timers.filter(t => t.tick());
		if (timers.length != 0) {
			setTimeout(tick, 1000);
		}
	}
	
	mw.hook('wikipage.content').add($content => {
		const $targets = $content.find('time.countdown-timer:not(.managed)');
		if ($targets.length == 0) {
			return;
		}
		
		$targets
			.addClass('managed')
			.each(() => {
				const timer = new CountdownTimer($(this));
				timers.push(timer);
			});
			
		tick();
	});
});