简体   繁体   中英

How to introduce delay into an HTML component using JavaScript

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 class="question">{{ d['message'] }}</li>
       {% else %}
           <li id ="answer-text" class="answer">{{ 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?

You could try using setTimeout() .

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 class="question">Q1</li> <li id="answer-text" class="answer hide">A1</li> <li class="question">Q2</li> <li id="answer-text" class="answer hide">A2</li> <li class="question">Q3</li> <li id="answer-text" class="answer hide">A3</li> <li class="question">Q4</li> <li id="answer-text" class="answer hide">A4</li> <li class="question">Q5</li> <li id="answer-text" class="answer hide">A5</li> </ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM