// processing messages
// messages to be processed
var messages = [{
id: 1,
from: "David",
text: "Test 1"
}, {
id: 2,
from: "David",
text: "Test 2"
}, {
id: 3,
from: "David",
text: "Test 3"
}, {
id: 4,
from: "David",
text: "Test 4"
}, {
id: 5,
from: "David",
text: "Test 5"
}, {
id: 6,
from: "David",
text: "Test 6"
}];
// how many messages the container acepts?
var maxMessages = 3;
// how many messages the container has?
var messageCounter = 0;
// what is the index of the message that is being currently processed
var currentIndex = 0;
// the messages that was processed (It will work like a queue (FIFO)
var processedMessages = [];
// processes one message for each 3 seconds
setInterval( function(){
// the current message
var message = messages[currentIndex++];
// is there a message to process?
if ( message ) {
// yes, there is!
// first, removes the oldest if the max quantity was reached
if ( messageCounter == maxMessages ) {
// the container now will have minus one message
messageCounter--;
// what is the oldest one?
// removes from the queue head
var oldest = processedMessages.pop();
// removes from the container
$( "#message_" + oldest.id ).remove();
}
// new message incoming!
messageCounter++;
// inserts the new message at the queue tail
processedMessages.unshift( message );
// inserts the message in the container
$( "#chat" ).append( "<div id='message_" + message.id + "'>From " +
message.from + ": " + message.text + "</div>" );
} else {
// there is no message
currentIndex--;
}
}, 3000 );
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.