0

我目前有一个倒数计时器,每 30 秒刷新一次图像。这段代码对我来说效果很好。

<script type="text/javascript">
jQuery(document).ready(function() {
var countdown = 30;
jQuery('#countdown').html(countdown);
setInterval(function() {
    countdown--;
    jQuery('#countdown').html(countdown);
            if (countdown <= 0)
    {
        jQuery('.imagerefresh').attr('src', jQuery('.imagerefresh').attr('src'));
        countdown = 30;
        jQuery('#countdown').html(countdown);
            }
}, 1000);
});
</script>

我正在尝试添加下面的代码以在 10 秒标记处获取新图像并将其保存在本地服务器上。当我将它添加到上面的代码中时(在第 7 行之前,“if (countdown <=0)”),它似乎获得了新图像并将其保存在 10 秒标记处,但在 0 秒时图像刷新图像似乎刷新然后立即自行折叠。

if (countdown <= 10)
{
     jQuery.get('/path/to/file/getnewimage.php');
}

关于如何修复图像崩溃的建议?或者关于更有效的代码的建议,以便在页面上刷新之前获取新图像。谢谢。

4

1 回答 1

0

停止使用 setInterval怎么样(http://www.youtube.com/watch?feature=player_detailpage&v=i_qE1iAmjFg#t=462s):

http://jsfiddle.net/coma/2Jaqy/7/

$(function() {

    var max = 30;
    var countdown = max;
    var img = $('#image');
    var display = $('#countdown');

    img.load(function(event) {

        setTimeout(refresh, 1000);

    });

    var load = function(url) {

        var ts = (new Date()).getTime();
        img.attr('src', url + '?ts=' + ts);

    };

    var get = function() {

        //$.get('/path/to/file/getnewimage.php', load);
        setTimeout(function() {

            load('http://lorempixel.com/400/200/');

        }, 500);

    };

    var refresh = function() {

        display.text('wait ' + countdown + ' seconds...');
        countdown--;

        if(countdown < 0) {

            countdown = max;
            get();

        } else {

            setTimeout(refresh, 1000);

        }

    };

    get();

});

并注意图像加载。

于 2013-06-02T11:08:00.473 回答