jQuery: setInterval

前端 未结 4 1007
日久生厌
日久生厌 2020-12-17 18:58

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: m

相关标签:
4条回答
  • 2020-12-17 19:45

    The problem is probably that the browser has loaded random.php into the cache. I think you'd be better off giving each image it's own url and using that. Then a php page can present just the src:

    var refreshId = setInterval(function () {
      $.get('random-src.php', function (result) {
        $('#center>img').attr('src') = result;
      },'text');
    },5000);
    

    Then random.php could return img/img1.jpg, img/img2.jpg, etc at random.

    Alternatively, you could stick header("Cache-Control: no-cache, must-revalidate"); towards the top of your random.php file to prevent the browser from caching.

    0 讨论(0)
  • 2020-12-17 19:47

    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.

    0 讨论(0)
  • 2020-12-17 19:48

    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.

    0 讨论(0)
  • 2020-12-17 20:05
    <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.

    0 讨论(0)
提交回复
热议问题