jQuery / PHP - Lazy loading gallery keeps trying to fetch images even when they've all loaded
<p>I've got an image gallery that is showing one image per row inside of a div. I don't want the next image to load until it reaches the edge of the viewport (to save on server resources). All the images are named sequentially in the same folder (img/1.jpeg, img/2.jpeg, img/3.jpeg, ...).</p>

<p>I'm using a modified jQuery plugin to do this, but it still keeps trying to fetch the next image after all the images in the directory have been loaded. <strong>It's the last if statement I'm having trouble with here.</strong></p>

<p>How do I stop the function from running once the last image in the directory has loaded?</p>

<pre><code>&lt;?php 
// Count total number of images in the directory
$directory = "img/";
$totalImages = count(glob("" . $directory . "*.jpeg"));
?&gt;

&lt;script type="text/javascript"&gt;
$('document').ready(function(){
    scrollalert();
});
function scrollalert(){
    var scrolltop=$('#scrollbox').attr('scrollTop');
    var scrollheight=$('#scrollbox').attr('scrollHeight');
    var windowheight=$('#scrollbox').attr('clientHeight');
    if(scrolltop&gt;=(scrollheight-(windowheight)))
    {
        // Fetch next image
        var nextImgNum=$('#content img').length + 1;
        $('#content').append('&lt;img src=\"book1/'+nextImgNum+'.jpeg\" /&gt;&lt;br /&gt;');
        updatestatus();
    }

    if(nextImgNum&lt;=&lt;?php echo $totalImages ?&gt;)
    {
        setTimeout('scrollalert();', 0); 
    }
}

&lt;/script&gt;
</code></pre>

<p>Any tips to optimize this script are greatly appreciated too :)</p>
