Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird infinite loop bug in jquery recursive function

I have a strange issue on the project I'm working with. This changes an image source and a content of a div automatically.

I have coded a function, but it falls into infinite loop and page does not load (page is showing the loading page always).

These are the codes:

$.fn.extend({
    changehaber: function(a){
     $('#cokokunanlarcontent').fadeOut('slow',function() {
           $('.jquerycokokunanlarbutton').attr('src','images/sabah/buton-pasif.png');
           $('img[rel="'+a+'"]').attr('src','images/sabah/buton-aktif.png'); 
        }).html($('#'+a).html()).fadeIn('slow');
        return this;
    }
});

function slidecokokunanlar() {
    $('#cokokunanlarcontent').html($('#cokokunanlar1').html()).delay(3000).changehaber('cokokunanlar2').delay(3000).changehaber('cokokunanlar3').delay(3000).changehaber('cokokunanlar4').delay(3000).changehaber('cokokunanlar5').delay(3000);
    slidecokokunanlar();
}

slidecokokunanlar();

What's the issue here, when this is executed, I want the function to work infinitely, but the page shows it's always loading. This is the console's output:

Uncaught RangeError: Maximum call stack size exceeded

Thanks in advance

like image 581
Arda Avatar asked Jul 23 '26 22:07

Arda


1 Answers

You can't call a function from inside itself without blocking up the whole execution stack. By calling the function from inside itself, you're effectively preventing it from ever returning, and as Javascript is single-threaded, everything will grind to a halt!

Change your function to this:

function slidecokokunanlar() {
    $('#cokokunanlarcontent').html($('#cokokunanlar1').html()).delay(3000)...
    setTimeout(slidecokokunanlar, 0);
}

This allows for concurrent execution without blocking the UI, thus allowing your page to remain responsive.

See this article on "chunking" for more information on how this works.

like image 69
chrisfrancis27 Avatar answered Jul 26 '26 11:07

chrisfrancis27