3xanax
3xanax

Reputation: 21

Load one line of json data every second

Im trying to display data every second from json file which look like this:

{
"messages": [{
    "time": "00:00:01",
    "color": "#ff4500",
    "nickname": "example1",
    "message": "LOL"
}, {
    "time": "00:00:02",
    "color": "#5f9ea0",
    "nickname": "example2",
    "message": "WTFFFF"
}, {
    "time": "00:00:05",
    "color": "#5f9ea0",
    "nickname": "example5",
    "message": "hello"
}]}

and get effect like this in html:

html

Upvotes: 0

Views: 67

Answers (1)

ptothep
ptothep

Reputation: 395

You could do something like this

let data = {
  "messages": [{
    "time": "00:00:01",
    "color": "#ff4500",
    "nickname": "example1",
    "message": "LOL"
  }, {
    "time": "00:00:02",
    "color": "#5f9ea0",
    "nickname": "example2",
    "message": "WTFFFF"
  }, {
    "time": "00:00:05",
    "color": "#5f9ea0",
    "nickname": "example5",
    "message": "hello"
  }]
}

let msg = document.querySelector("#messages")

let display = ([x, ...rest]) => {
  if (!x) return
  setTimeout(_ => {
    msg.innerHTML += `<p>
    <span>${x.time}</span>
    <b><span style="color: ${x.color}">${x.nickname}</span></b>:
    <span>${x.message}</span></p>`
    display(rest)
  }, 1000)
}

display(data.messages)
<div id="messages"></div>

Upvotes: 1

Related Questions