March 23, 2012
Jquery SetTimeout issue (I know posts already exists…)
Question by Marc
I have a table with one column and four rows. Each tr has a class called ‘ligne’. I also have a button. When clicked, I would like to run a each loop on the class ‘ligne’. For each item I would like to give a blue background, but after sleeping for 1 second. I read a lot of posts, applied what i read, but it is not working. Hope someone can help me understand. Cheers. Marc
my html:
<table>
<tr class="ligne">
<td>one</td>
</tr>
<tr class="ligne">
<td>two</td>
</tr>
<tr class="ligne">
<td>three</td>
</tr>
<tr class="ligne">
<td>four</td>
</tr>
</table>
<input id="btn-timeout" type="submit" value="timeout!"/>
my js:
$(document).on({
click: function() {
$(".ligne").each(function() {
setTimeout(function() {
$(this).css('background', 'blue');
}, 1000);
});
}
}, "#btn-timeout");
Answer by Tim Medora
Here’s a version which highlights each cell one by one: http://jsfiddle.net/M2ZCh/9/
$(document).on({
click: function() {
var index = 0;
$(".ligne").each(function() {
var obj = $(this); // pin reference to element
setTimeout(function() {
obj.css('background', 'blue');
}, 1000 * ++index);
});
}
}, "#btn-timeout");
Answer by Starx
You can do this, as this
$("#btn-timeout").click(function() {
window.setTimeout(function () {
$(".ligne").css("background","blue");
}, 1000);
});
Update:
If you want each boxes to changed background consequently then, you have to use setInterval()
instead.
var tlenth = $(".ligne").length;
$("#btn-timeout").click(function() {
var i = 0;
var int = setInterval(function () {
$(".ligne").eq(i).css("background","blue");
i++;
if(i>tlenth-1) { clearInterval(int); }
}, 1000);
});