最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change text multiple times at different intervals? - Stack Overflow

programmeradmin2浏览0评论

So let's say you have something like this..

HTML:

<p id="text"></p>

JS:

setTimeout(function() {$('#text').html("First sentence");}, 1000);
setTimeout(function() {$('#text').html("Second sentence");}, 2000);

Is there any way you can display like ten of these sentences without having to write the same line of code ten times? I can't figure it out..

So let's say you have something like this..

HTML:

<p id="text"></p>

JS:

setTimeout(function() {$('#text').html("First sentence");}, 1000);
setTimeout(function() {$('#text').html("Second sentence");}, 2000);

Is there any way you can display like ten of these sentences without having to write the same line of code ten times? I can't figure it out..

Share Improve this question asked May 1, 2016 at 22:46 user298519user298519 1,1901 gold badge12 silver badges27 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 2

Create a closure over i and throw a party.

var $text = $("#text");
var numbers = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", "Tenth"];

for (var i = 1; i <= 10; ++i) {
  (function(index) {
    setTimeout(function() { 
      $text.html(numbers[index-1] + " sentence");
    }, i * 1000);
  })(i);
}

https://jsfiddle/9z4r1qqk/

Something like:

for(var i = 1; i < 10 ; i++) {
    setTimeout(function() {$('#text').html("Sentence #" + i);}, i * 1000);
}

If you don't need the sentence to have exactly that format.

var sequence = [
  ['first sentence',1000],
  ['second sentence',2000]
];

var $target = $('#text');

sequence.map(function(v,i,a){
  return setTimeout(function(){
    $target.innerHtml(v[0]);
  },v[1]);
});

This will run as a loop and only show the next sentence after the last one is plete.

Sample here

var a = [
  "test 1",
  "test 2",
  "test 3",
  "test 4",
  "test 5"
];

(function update(idx) {

    $("#text").html(a[idx]);
    setTimeout(update, 1000, ((++idx) % a.length));

})(0);

Seem like map is what You are looking for.

const $elem = $('#text');

[
  ['First sentence', 1000],
  ['Second sentence', 2000],
].map(([text, delay]) => setTimeout(() => $elem.text(text), delay));

It would also be a good idea to store a pointer to an element in a variable, so the browser would do the search just once.

You also might want to switch to text method if the content You want to set is just strings.

Disclaimer: this code is written in ES6, so it won't be working in IE (but will in Edge) and Safari.

var sentences = ['First sentence', 'Second sentence', 'Some other sentence'];
var timerId = null;

function nextSentence() {
  var sentence = sentences.shift();
  $('#text').text(sentence);

  if (sentences.length == 0) {
    window.clearInterval(timerId);
  }
}

timerId = window.setInterval(nextSentence, 1000);
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="text"></p>

Just add the sentences you want to display to the sentences variable and they should change approximately every second.

If this is all you need to do, you can probably remove the jQuery dependency by replacing $('#text').text(sentence); with document.getElementById('text').textContent = sentence;.

When you don't want to type the same thing multiple times, perhaps in multiple places, create a plugin that is easy to use instead

$.fn.queuedText = function(text, delay) {
    var self = this;
    text = Array.isArray(text) ? text : [text];
    
    $.each(text, function(_, txt) {
       self.delay(delay).queue(function (next) { 
           self.text(txt);
           next(); 
       });
    });
    
    return self;
}

// To be used as ..........->

$('#text').queuedText([
    "First sentence",
    "Second sentence",
    "Third sentence",
    "Fourth sentence",
    "Fifth sentence",
    "Sixth sentence",
    "Seventh sentence",
    "Eight sentence",
    "Ninth sentence",
    "Tenth sentence"
], 1000);
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text"></div>

发布评论

评论列表(0)

  1. 暂无评论