Add text to div from array and remove it after X seconds
I am working with JQuery for the first time trying to figure something out with no luck. I am trying to do this:
- Get the value from the array and print it to a div.
- Wait X seconds and remove the text from the div.
- Go to the next value from the array and repeat the process as long as there are values ββin the array.
I got the following code which displays all values ββfrom an array and after 3 seconds it deletes everything I don't want:
Div looks like this:
<div id="loader"></div>
The script looks like this:
var cars = ["Saab", "Volvo", "BMW"];
for(var i=0; i<cars.length; ++i){
$("#loader").append(cars[i] +"<br/>");
setTimeout(function() {
$( "#loader" ).empty();
}, 3000);
}
source to share
You need to update your code to
var cars = ["Saab", "Volvo", "BMW"];
var i = 0;
function paintCar(){
$( "#loader" ).empty();
if(i != cars.length) {
if(i < cars.length) {
$("#loader").append(cars[i] +"<br/>");
}
setTimeout(function() {
paintCar();
}, 3000);
}
i++;
}
paintCar();
For reference - http://plnkr.co/edit/NPqDpXHPYoBCNOgDK5d6?p=preview
source to share
Here I have a nice alternative that uses setInterval instead of setTimeout to avoid using loops
var cars = ["Saab", "Volvo", "BMW"];
var i = 0;
var interval = setInterval(function(){
if(i < cars.length){
$( "#loader" ).text(cars[i]);
i++;
}else{
// stop the timer
interval = null;
}
},3000);
source to share
SetTimeout
Anything you pack inside setTimeout
will be executed after the specified timeout. In your example
setTimeout(function () {
$("#loader").empty();
}, 3000);
SetTimeout clears everything after 3 seconds. Instead, you need to load each item in 3 seconds.
$ (document) .ready ()
I don't see it $(document).ready()
in your question, I assume you used it but didn't mention it, or that your script was included at the end of the document. When using jQuery, you need to make sure the page has been rendered before you can use DOM selector elements.
Sample code
Try the following:
var cars = ["Saab", "Volvo", "BMW"];
$(document).ready(function () {
loadItem(0);
});
function loadItem(index) {
if (index < cars.length)
{
$('#loader').html(cars[index]);
setTimeout(function () {
loadItem(index + 1);
}, 1000);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="loader"></div>
source to share
You can avoid setTimeout
everything by combining jQuery delay()
and queue()
:
var cars = ['Saab', 'Volvo', 'BMW'];
$.each(cars, function(_, val) { //for each car ...
$('#loader')
.delay(1000) //wait 1 second
.queue(function(next) { //add to queue
$(this).html(val); //output car
next(); //continue with the next queued item
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loader"></div>
source to share