Reputation: 13
I got this line here and I'm really really struggling hard with executing the is offline part once.
It shows once, when the user is online. That's okay. But when the user turns offline it says --- is offline
every 10 seconds in the console. I only want it to say is offline
when the user turns offline and then stop until it's online again. Please help me out here.
window.setInterval(function() {
if (document.getElementById('statusIndexer') == null)
return;
for (var i = 0; i < WLAPStore.Presence.models.length; i++) {
var m = WLAPStore.Presence.models[i];
var id = 'p' + m.id.slice(0, -5);
var clientBox = document.getElementById(id);
if (clientBox !== null) {
var img = clientBox.getElementsByTagName('img')[0];
img.classList.remove('isOnline');
if (m.isOnline) {
console.log(id + ' is online');
clientBox.parentNode.prepend(clientBox);
img.classList.remove('isOffline');
img.classList.add('isOnline');
} else {
console.log(id + ' is offline');
clientBox.parentNode.prepend(clientBox);
img.classList.remove('isOnline');
img.classList.add('isOffline');
(document.getElementById('statusIndexer') == null)
return;
}
}
}
}, 1000);
Upvotes: 0
Views: 100
Reputation: 780724
Use a global variable to hold the previous state, and check if it changed before logging the message.
var onlineState = {};
window.setInterval(function() {
if (document.getElementById('statusIndexer') == null)
return;
for (var i = 0; i < WLAPStore.Presence.models.length; i++) {
var m = WLAPStore.Presence.models[i];
var id = 'p' + m.id.slice(0, -5);
var clientBox = document.getElementById(id);
if (clientBox !== null) {
var img = clientBox.getElementsByTagName('img')[0];
img.classList.remove('isOnline');
if (m.isOnline) {
if (m.isOnline !== onlineState[id]) {
console.log(id + ' is online');
}
clientBox.parentNode.prepend(clientBox);
img.classList.remove('isOffline');
img.classList.add('isOnline');
} else {
if (m.isOnline !== onlineState[id]) {
console.log(id + ' is offline');
}
clientBox.parentNode.prepend(clientBox);
img.classList.remove('isOnline');
img.classList.add('isOffline');
(document.getElementById('statusIndexer') == null)
return;
}
onlineState[id] = m.isOnline;
}
}
}, 1000);
Upvotes: 1