Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: setInterval

I want to make a slideshow on my site, but the problem is that the setInterval works only one time. It loads my file only one time end then stops.

Heres the code: main.html

<img src="images/ex/full.jpg" width="800" height="377" alt="">
<script>
    $(document).ready(function(){
        var refreshId = setInterval(function(){
            $('#center').load('images/gallery/best/rotate.php');
        }, 5000);
    });
</script>

rotate.php

<img src="images/gallery/best/random.php?".<?php echo rand(0,1000) ?>."" width="800" height="377" alt="">

random.php contains a code which loads random image from selected folder, it works good.

Forgot to mention, I got lightbox scripts included too. Maybe they don't work together?

Head:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="vendors/jquery/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="vendors/js/prototype.js"></script>
<script type="text/javascript" src="vendors/js/scriptaculous.js?load=effects,builder"></script>
<script type="text/javascript" src="vendors/js/lightbox.js"></script>
<link rel="stylesheet" href="styles/style.css" type="text/css" />
<link rel="stylesheet" href="styles/lightbox.css" type="text/css" />

Thanks.

like image 512
Tom Avatar asked Dec 04 '10 18:12

Tom


3 Answers

<script>
$(document).ready(function(){
    var refreshId = setInterval(function(){
    var r = (-0.5)+(Math.random()*(1000.99));
        $('#center').load('images/gallery/best/random.php?'+r);
    }, 5000);
});
</script>

How about that?

--

Edit

Sorry, I meant that you should just randomize the photos in the setInterval function. As illustrated above. Instead of rotate.php; just load random.php.

like image 77
bozdoz Avatar answered Nov 15 '22 17:11

bozdoz


Expanding on my comment, if it is a caching issue, then you can update your code with

<script>
$(document).ready(function(){
    var refreshId = setInterval(function(){
        $('#center').load('images/gallery/best/rotate.php?' + new Date().getTime());
    }, 5000);
});
</script>

Which will cause the url to be different on each request and hence will avoid your caching issue.

like image 32
Blair McMillan Avatar answered Nov 15 '22 19:11

Blair McMillan


There problem is not the setInterval, it's the caching of the image. When the image tag is loaded, it looks exactly like the one before. The browser doesn't load the image again, it just uses the one that is already loaded.

If you want to load the image again, change your rotate.php to include a counter or random number as parameter in the URL, returning something that for example looks like this:

<img src="images/gallery/best/random.php?98037465936" width="800" height="377" alt="">

By changing the URL each time the tag is loaded, the browser has to load the new image each time.

like image 39
Guffa Avatar answered Nov 15 '22 18:11

Guffa