开发者

Attention JavaScript gurus: Need a hand with setInterval()

I am trying to make a non interactive display for a real estate shop window.

It's been a while since I've played with setInterval().

The first time my script steps through, it is fine. But when it tries to get the next property via getNextProperty(), it starts to go haywire. If you have Firebug, or an equivalent output of console.log(), you'll see it is calling things it shouldn't!

Now there is a fair bit of JavaScript, so I'll feel better linking to it than posting it all.

Store 开发者_C百科Display

Offending JavaScript

It is worth mentioning all my DOM/AJAX is done with jQuery.

I've tried as best to make sure clearInterval() is working, and it seems to not run any code below it.

The setInterval() is used to preload the next image, and then display it in the gallery. When the interval detects we are at the last image ((nextListItem.length === 0)), it is meant to clear that interval and start over with a new property.

It has been driving me nuts for a while now, so anyone able to help me?

It is probably something really obvious!

Many thanks!

Update

Well, now I feel better to know the problem was my naiveness of assuming plugins would work out of the box.

I did get this plugin from an answer on Stack Overflow. I have alerted the author of this question.

Thanks for all your answers!


Here's your problem area:

jQuery.extend(jQuery, {
  imagesToLoad: 0,

The problem is that this variable is global/shared (jQuery.imagesToLoad), so this check later on:

if(jQuery.loadedImages.length >= jQuery.imagesToLoad){

Depends on this plugin not being called twice at the same time, otherwise that if check goes nuts, since you're calling this later in your code:

$.preloadImages({
  urls: [nextImage],

That count drops to 1, making the if evaluate to true not just on the last image, but all the images after the first in sets after the first (due to when the callback runs, it overlaps in time), which causes the complete callback to fire many times, not just once, so this code:

$.preloadImages({
 urls: preloadImages,
 complete: function() { showProperty(property); }
});

...sees that complete function running many times, so you're starting many intervals at the same time (this is why you see console.log('show property called' + property.slug) execute so many times in the log).

Short fix: replace the preloadImages code with a version that doesn't use a global variable :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜