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..
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.net/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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With