cancelling a function with an external event in javascript/jQuery
<p>I have a situation where we are progressively showing higher and higher quality images to a user as they download.</p>

<p>The logic looks like this:</p>

<p>3 Image formats : low quality (5-8kb), large (60-80kb), highres (150-250kb).</p>

<ol>
<li>Check if large or high res photo is cached if so simply initially show cached version and FINISH.</li>
<li>If not load low quality image and display to the user straight away.</li>
<li>precache large image and change img.src once it has loaded.</li>
<li>Check users window size if it exceeds a certain threshhold, precache highres image and change img.src on load.</li>
</ol>

<p>Everything works beautifully.</p>

<p>However during the high res download if a user clicks to go to the next image, everything will of course get screwed up since we have set an event to occur onload when the previous highres image has loaded.</p>

<p>Essentially the onload event is occurring after the user has already clicked to go onto the next image, meaning that the NEW image is getting replaced with the old one.</p>

<p>What I need to do is be able to cancel the function whenever a user changes to the next photo.</p>

<p>The function looks something like this:</p>

<pre><code>(function(index){
        $(highresimage).imagesLoaded(function(){
                    setTimeout(function(){
                        self.cache.image = $(highresimage).appendTo(self.cache.imagewrap);
                        self.cache.photos[index]['highresloaded'] = true;
                        setTimeout(function(){
                        self.cache.imagewrap.children('img').first().remove();
                        self.cache.image.css({
                            'left':'',
                            'position':'relative'
                        });
                        },10);
                    },200);
        });
})(index);
</code></pre>

<p>So I need to be able to programmatically cancel the <code>$(highresimage).imagesLoaded(function(){});</code></p>

<p>What would be the best way of achieving this?</p>

<p>Thanks in advance.</p>

<p><strong>EDIT:</strong> Please note in my example we are actually cloning the image, changing the src, adding it to the dom, leaving a few ms then removing the old image.  This is down to a bug in Firefox which causes flashing when changing the src of high resolution images.  As horrible as it is, removing the ugly timeouts makes the experience far worse for the user in Firefox.  They are there for a reason. :P</p>
