JQuery $ .post causes browser stack overflow

I have the following jQuery code:

var id_atual
var temp_id
var tempo_flash = 50
var $slide_atual = $('#slider .atual')
var $slide_prox = $('#slider .ocultar')
setInterval(function(){
    id_atual = $slide_atual.attr('alt')
    $.post('get_banner.php', {atual: id_atual}, function(proximo){
        temp_id = proximo.split(';;')
        $slide_prox.attr('src', temp_id[0]).load(function(){
            $slide_atual.hide('fade', tempo_flash, function(){
                $slide_atual.attr('alt', temp_id[1]).attr('src', temp_id[0]).load(function(){
                    $slide_atual.show('fade', tempo_flash)
                })
            })
        })
    })
}, 4000)

      

And the following HTML code:

<div id="slider">
    <img src="imagens/slider/imagen-slider.jpg" alt="1" class="atual"/>
    <img src="" alt="" class="ocultar" />
</div>

      

If class .ocultar has

display: none;

      

vars tempo_flash is only animation timing and get_banner.php file is only for getting next banner from mysql database. It has been tested and works fine. The problem is that after a small change (4 or 5 banners) the browser stops responding (for Firefox Chrome and Opera) and in IE I get a warning Qaru at line: 3

and the javascript of the whole page stops working.

Any help is appreciated!

+3


source to share


2 answers


Within each iteration of the setInterval () ed function, you assign the event to the .load()

owner of the image location. Assigning an event to an object does not delete existing ones !



So in the second iteration, the image holder will have two event handlers .load()

, then three, and so on; and every time the image is loaded it is lit by all the event handlers attached to the event .load()

. You probably need to refactor your code, perhaps by assigning the event handler .load()

only once (and using semicolons).

+3


source


you shouldn't use setInterval, you should use setTimeout inside a function and execute it on the $ .post callback, something like:

var id_atual
var temp_id
var tempo_flash = 50
var $slide_atual = $('#slider .atual')
var $slide_prox = $('#slider .ocultar')
function tictac(){
    setTimeout(function(){
        id_atual = $slide_atual.attr('alt')
        $.post('get_banner.php', {atual: id_atual}, function(proximo){
            temp_id = proximo.split(';;')
            $slide_prox.attr('src', temp_id[0]).load(function(){
                $slide_atual.hide('fade', tempo_flash, function(){
                    $slide_atual.attr('alt', temp_id[1]).attr('src', temp_id[0]).load(function(){
                        $slide_atual.show('fade', tempo_flash)
                    })
                })
            })
        })
        ticktac();
    }, 4000);
}

      



this way, only 4 seconds will start counting, if and when the response from the server is complete, you won't have overflow problems.

0


source







All Articles