Sync event triggers on interval
by Paulo Ávila
HTML
<pre id="console"></pre>
JavaScript
var nCounter = 0,
intervals = [],
INTERVAL = 1800;
// these simulate notifications wanting to be triggered at different, sequential times
setTimeout(triggerNotification, 0);
setTimeout(triggerNotification, 1000);
setTimeout(triggerNotification, 3400);
// helps with the visualization of the "grouped" console messages
// by showing a divider on the same interval
/*
intervals.push(setInterval(function () {
$('#console').append('-----\n');
}, (INTERVAL)));
//*/
// triggers the notification only after a certain offset
// in order to line it up with the correct interval markers
function triggerNotification() {
var nNo = ++nCounter,
now = new Date(),
ticToc = Math.floor((now.getTime() / INTERVAL) % 2),
displayOffset = (INTERVAL - (now.getTime() % INTERVAL));
// additional offset to control the correct "side" of a notification to be shown first
// adds an extra window interval if the upcoming window isn't even
// insures the beginning is a "tic" and never a "toc"
displayOffset = (displayOffset + (ticToc === 0 ? 0 : INTERVAL));
$('#console').append("Waiting for upcoming window (in " + displayOffset + "ms) to put n" + nNo + ' into the queue...\n');
setTimeout(function () {
intervals.push(setInterval(function () { displayNotification(nNo) }, INTERVAL));
displayNotification(nNo);
}, displayOffset);
}
// actually prints the notification to the console with a
// timestamp (accurate to: HH:MM:SS:MS)
function displayNotification(n) {
var now = new Date(),
ticToc = Math.floor((now.getTime() / INTERVAL) % 2);
$('#console').append((ticToc === 0 ? '+' : '-') + 'n' + n + ' (' + now.getUTCHours() + ':' + now.getUTCMinutes() + ':' + now.getUTCSeconds() + ':' + now.getUTCMilliseconds() + ')\n');
}
// stops the repetition of the interval after 10 windows
setTimeout(function () {
$('#console').append("\n... I think I've made my point :-)\n");
...