Jordan Adams
Jordan Adams

Reputation: 434

Stop setTimeout delaying first run

So I'm creating a script which adds clouds floating across the page on my website. However as seen in this example, the first cloud's appearance is delayed (10-12 seconds) by the setTimeout in spawn_cloud_loop. Is there any way to force the first cloud to be added instantly without the delay. I have tried adding add_cloud(); before spawn_cloud_loop(); but the delay is still there. The project as a whole can be found at https://github.com/JordanAdams/jordanadams.github.com and the code for the cloud effect in js/clouds.js.


Jordan

Upvotes: 0

Views: 303

Answers (1)

nnnnnn
nnnnnn

Reputation: 150080

Your clouds.js script is included in the head and then add_cloud(); is run immediately. Which means you create a new cloud and try to append it to the "clouds" div which doesn't exist because it hasn't been parsed yet. The second and subsequent clouds are created OK because the spawn_cloud_loop() function has such a long delay that the document has been parsed by the then.

You need to either move the clouds.js script inclusion down somewhere below the "clouds" div in your page source or put the add_cloud(); call in a document ready handler so that it isn't executed until after the "clouds" div has been parsed:

$(document).ready(function(){
    add_cloud();
    spawn_cloud_loop();
    clean_up();
});

Note: you wouldn't need the initial call to add_cloud() if you modified your spawn_cloud_loop() to call add_cloud() before setting the timeout:

function spawn_cloud_loop () {
    add_cloud();
    setTimeout(spawn_cloud_loop, rand(10000, 12000));
}

(Of course you'd still need to call spawn_cloud_loop() from a document ready.)

Also, you wouldn't need a clean_up() process at all if you delete each cloud immediately at the end of the animation from the jQuery .animate() method's complete callback:

cloud.animate({ left: window.screen.width+100 },
              50000,
              'linear',
              function(){ $(this).remove(); });

Upvotes: 4

Related Questions