Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to check 2000 checkboxes in Javascript?

I've got a webpage with a couple thousand checkboxes on it, and would like to add a "Check all" feature. Unfortunately, my current implementation hangs Google Chrome for at least five seconds.

Here is what I have tried (using jQuery):

$('input').attr('checked', true); // as well as...
$('input').click();

I believe that the actual Javascript runs fast, however the browser might be having trouble rendering all the updates so quickly. Could I be doing something else?

Here is a simplified example: https://www.msu.edu/~weinjare/checkboxes.html

I've also ran the Profiler built-in to Chrome and got these results: Profiler results

like image 534
Jared Avatar asked Feb 01 '11 05:02

Jared


1 Answers

Accessing the DOM attributes directly may be faster, though my guess is that it won't be significantly faster:

var els = $('input');
for (var i = 0; i < els.length; i++) {
    els[i].checked = true;
}

But as you say, the biggest problem is probably the rendering. You could try batching the execution within setIntervals of 0 milliseconds. This won't speed anything up, but at least will stop the "hanging":

var els = $('input'), i = 0;
var interval = setInterval(function () {
    var batchLen = i + 100 > els.length ? els.length : i + 100;
    for (; i < batchLen; i++) {
        els[i].checked = true;
    }
    if (i === els.length) clearInterval(interval);
}, 0);
like image 180
David Tang Avatar answered Sep 22 '22 11:09

David Tang