Home > Back-end >  How to intorduce delay into an HTML component using JavaScript
How to intorduce delay into an HTML component using JavaScript

Time:12-06

I've created a chat box using HTML and it display a question and a relevant answer in two different rows. However, both question and answer appear at the same time and I'd like to introduce a little bit of time lag between the question and the answer. For example, the question should pop up first and then the answer shows up as soon as the question is printed out. Here's my html code:

{% for d in chatlist %}
       {% if d['text_type']=='question'%}
          <li >{{ d['message'] }}</li>
       {% else %}
           <li id ="answer-text" >{{ d['message'] }}</li>
       {% endif %}
{% endfor %}

I'd like to introduce a time delay to the element whose id = "answer-text". Is it possible to write a Javascript function for time delay and apply the function only to the answer text element?

CodePudding user response:

You could try using setTimeout().

CodePudding user response:

You might want to use setTimeout() to delay when some items of your HTML are displayed.

I have added a sample usage below where each answer is displayed every seconds while all the questions are shown from the start.

I accomplished the show/hide by adding a CSS class at the start and removing it at the end of the timeout delay.

See demo:

let one_second = 1000; // in milliseconds

let answers = document.getElementsByClassName('answer');

for (let idx = 0; idx < answers.length; idx  ) {
  setTimeout(function() {
    answers[idx].classList.remove('hide');
  }, one_second * (idx   1));
};
.question {
  border-bottom: 1px solid grey;
}

.answer {
  margin-bottom: 10px;
  color: blue;
}

.hide {
  visibility: hidden;
}
<ul>
  <li >Q1</li>
  <li id="answer-text" >A1</li>

  <li >Q2</li>
  <li id="answer-text" >A2</li>

  <li >Q3</li>
  <li id="answer-text" >A3</li>

  <li >Q4</li>
  <li id="answer-text" >A4</li>

  <li >Q5</li>
  <li id="answer-text" >A5</li>

</ul>

  • Related