Maxim Ershov
Maxim Ershov

Reputation: 1284

jQuery timeout inside function

Here is my code. What I am trying to do is to update news at my page using jQuery. The code works as intended - every 5 seconds it removes news from sidebar and posts 2 updates at their place. What I cannot do is to make it remove all news before posting updates. For now it appends updates and starts fading out old news at the same time. Anyone has ideas of how to set the proper timeout for this?

function updateNews()
{

    $('.newsUpdate').load('news.html .news', function ()
    {
        $('.MainNews').fadeOut(); /* timeout should happen here! */
        var start = Math.floor(Math.random() * 4);
        var stop = start + 2;
        $(this).children('.news').slice(start, stop).css('display', 'none').attr('class', 'MainNews').insertAfter('.nav').fadeIn().children('span').remove();
        $(this).children('.news').remove();
    });
    setTimeout(updateNews, 5000);
}
updateNews();

HTML is pretty simple:

<div class='sidebar'>
    <ul class='nav'>
        <li></li>
    </ul>
</div>
<article>main content of the site</article>
<div class='newsUpdate'>this created specially to upload news from news.html and manipulate them</div>

Upvotes: 0

Views: 603

Answers (1)

sdespont
sdespont

Reputation: 14025

Use the fadeOut callback

function updateNews()
{

    $('.newsUpdate').load('news.html .news', function ()
    {
        $('.MainNews').fadeOut(1000,function(){
            //This code will be executed after the fadeOut
            var start = Math.floor(Math.random() * 4);
            var stop = start + 2;
            $(this).children('.news').slice(start, stop).css('display', 'none').attr('class', 'MainNews').insertAfter('.nav').fadeIn().children('span').remove();
            $(this).children('.news').remove();
        });
    });
    setTimeout(updateNews, 5000);
}

updateNews();

Upvotes: 1

Related Questions