matonator
matonator

Reputation: 45

Repetitive iteration over JavaScript object with delay

I have JavaScript object with quotes and I have HTML element which will be filled by these quotes. I want every quote to be there for 5 seconds. Also I want it to be repeated. So when the last quote is used, function starts again. So far I have this.

var quote = document.getElementById("quote");
var quotes = {
    "q1": "q1",
    "q2": "q2",
    "q3": "q3"
}

function quoteChange(){
    for (var key in quotes){
        quote.innerHTML = quotes[key];      
    };
};
quoteChange();

Upvotes: 2

Views: 38

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370989

Use a setTimeout that repeatedly calls quoteChange:

var quote = document.getElementById("quote");
var quotes = {
    "q1": "q1",
    "q2": "q2",
    "q3": "q3"
}

let i = 0;
const quoteStrings = Object.entries(quotes);
function quoteChange(){
  quote.textContent = quoteStrings[i][0] + ' : ' + quoteStrings[i][1];
  i = (i + 1) % quoteStrings.length;
  setTimeout(quoteChange, 5000);
}
quoteChange();
<span id="quote"></span>

Not sure why quotes is an object, it would make more sense as an array, given what you're using it for.

Make sure to use textContent when you're setting text content - only use innerHTML when you're inserting an HTML string.

Upvotes: 1

Related Questions