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

http://jsfiddle.net/M2ZCh/

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);
});

Demo

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);
});

Demo

July 15, 2010

Will a page taking 2-3 mins to render cause a javascript 'taking too long' warning

Question by bcm

I’m using the jQuery document ready method – $(function()

If the page takes too long to render (say 2mins+), will this be the reason for the page throwing a javascript taking too long to execute error/warning?

Answer by Igor Zevaka

No. $(function(){}) will get called once the DOM is loaded – i.e. it doesn’t keep running throughout the load process. Unless you are trying to do a long running synchronous task or stuck in a long loop, you shouldn’t get that error.

Have a look at the CPU utilization. If it’s high for the browser, it’s a tell tale sign that there is an infinite loop somewhere.

Answer by Starx

No the document.ready only loads after the DOM is ready (i.e after the jquery core is loaded and ready to be used), so it will not throw any error, if a page takes 2-3 mins.

...

Please fill the form - I will response as fast as I can!