Help in jQuery need an infinite loop?

I have a problem with this code:

    var par = [];
    $('a[name]').each(function() {
        if (($(this).attr('name')).indexOf("searchword") == -1) {
            par.push($(this).attr('name'));
            $('.content').empty();
            for (var i = 0; i < par.length; i++) {
                $(".content").append('<a id="par" href="#' + par[i] + '">' + par[i] + '</a><br />');
            }
        }
    });

      

This also causes firefox to pop out the "Stop executing this script" warning window. But this only happens when there is a very large amount of data on the page. Any ideas how to fix this?

+2


a source to share


2 answers


Your code should look like this:

var par = [];
$('a[name]').each(function() {
    if (($(this).attr('name')).indexOf("searchword") == -1) {
        par.push($(this).attr('name'));
    }
});
$('.content').empty();
for (var i = 0; i < par.length; i++) {
    $(".content").append('<a id="par" href="#' + par[i] + '">' + par[i] + '</a><br />');
}

      

There is no reason for the second loop to be inside the first - it just causes a lot of unnecessary work.



You can make this code a little simpler by removing the array par

and the second loop and simply creating the content inside the first loop:

$('.content').empty();
$('a[name]').each(function() {
    var name = $(this).attr('name');
    if (name.indexOf("searchword") == -1) {
        $(".content").append('<a id="par" href="#' + name + '">' + name + '</a><br />');
    }
});

      

+4


a source


Browsers run all javascript (and most page interactions) on a single thread. When you run such a long loop without interruption, the UI is completely frozen. You should try to make your algorithm smaller, but in case that is not possible, you can use this trick where you do a little work, then pause and change the UI thread browser control a bit, then do the extra work.

var $targets = $('a[name]');
var current = 0;
var i = 0;
function doSomeWork() {
    if (i == $targets.length) return;

    var $t = $targets[i];
    if (($t.attr('name')).indexOf("searchword") == -1) {
        par.push($t.attr('name'));
        $('.content').empty();
        for (var i = 0; i < par.length; i++) {
            $(".content").append('<a id="par" href="#' + par[i] + '">' + par[i] + '</a><br />');
        }
    }
    i++;
    window.setTimeout(arguments.callee, 0);
}

      



This makes one iteration of your loop in the function before yielding. It might be nice to do more than one in a function call, but you can experiment with that. An article about this idea: http://www.julienlecomte.net/blog/2007/10/28/

0


a source







All Articles