Pregunta

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>

Where the class .ocultar have a

display: none;

The vars tempo_flash is only the animation time, and the file get_banner.php is only for getting the next banner from the mysql database. It is tested and working fine. The problem I have is that after a little (4 or 5 banner changing) the browser stops answering (for Firefox Chrome and Opera) and on IE I get an alert Stack overflow at line: 3 and the javascript of the whole page stops working.

Any help appreciated!

¿Fue útil?

Solución

Inside each iteration of the setInterval()ed function, you assign a .load() event to an image place holder. Assigning an event to an object does not remove existing ones!

So on second iteration, the image place holder will have two .load() event handlers, then three and so on; and every time the image is loaded, it will fire all event handlers attached to .load() event. You probably need to re-factor your code, perhaps by assigning the .load() event handler only once (and use semicolons).

Otros consejos

you shouldn't use setInterval, you should use a setTimeout inside a function, and execute it on the callback of the $.post, 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, the 4 seconds only start counting if and when the response from the server is complete, you will not have your overflow problems

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top