I have an array containing messages that I print to the screen randomly one at a time. I am using javascript to create a new DOM element ('p') and then to create a new text node that I attach to the new p element.
In order to not display a duplicate, I created a new array that will hold the new text that is displayed. Prior to printing to the screen, I check to make sure that the text that is about to be displayed is not currently in the new array so that I can check for duplicates.
It is never finding a duplicate however because each time it goes through the for loop it is creating another object (I believe it is a text node because each iteration through it will console log me the text nodes content +=1 each time. For instance, the first time might get:
"this is the message"
and the next console log I will get:
"this is the message" "this is the message"
and the next time:
"this is the message" "this is the message" "this is the message"
Here is the code I am using for that portion as I believe this is the only relevant code:
function randomMessages(){
var displayMessage = document.getElementById('front-message');
var newParagraph = document.createElement('p');
newParagraph.setAttribute('class', 'front-page-messages');
currentMessage = Math.floor(Math.random() * frontPageMessages.length);
var randomText = document.createTextNode(frontPageMessages[currentMessage]);
checkPastMessages(oldMessages, randomText, newParagraph); // check new array containing displayed messages for duplicates
newParagraph.appendChild(randomText);
displayMessage.appendChild(newParagraph);
newParagraph.style.position = "relative";
newParagraph.style.top = Math.floor(Math.random() * (window.innerHeight -430) ) + "px";
newParagraph.style.textAlign = "center";
newParagraph.style.fontFamily ="'Montserrat', sans-serif";
newParagraph.style.fontSize = "1.3em";
newParagraph.style.color = "#52A8EC";
oldMessages.push(randomText);
console.log(oldMessages);
window.setTimeout(function(){
displayMessage.removeChild(newParagraph);
newParagraph.removeChild(randomText);
randomMessages();
}, 5000);
}
randomMessages();
function checkPastMessages(oldMessages, randomText, newParagraph){
for(var i = 0; i < oldMessages.length; i++){
if(randomText == oldMessages[i]){
console.log('duplicate');
randomMessages();
}else{
console.log('not a duplicate');
console.log(randomText);
};
};
}
checkPastMessages()script finds a duplicate, it starts up a newrandomMessages()cycle. I don't understand why.nodeValues, or store the used indices (currentMessage).