javascript - 每 30 秒重置一次计数器

标签 javascript jquery ruby-on-rails jquery-plugins countdown

好的,我正在使用 jquery countdown plugin声明如下

$j(document).ready(function() {
$j('#clock').countdown( { to : "#{event.start_date.strftime("%Y:%m:%d:%H:%M")}", remaining : "#{event.start_date - Time.now}", display_on_complete : 'list', hide_on_complete : 'countdown' } );
});

这工作正常,但我需要每隔 30 秒从这个 ajax 调用中更新这个倒计时

$j(document).ready(function() {
    function refresh() {
    $j.ajax({
    type: "GET",
    url: "http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo&output=json",
    dataType: "jsonp",
    success: function(data){
    unix_timestamp = data.Result.Timestamp
    var json_date = new Date(unix_timestamp*1000);
    console.log(json_date);
    setTimeout(refresh, 30000);
    }
});

如您所见,日期是 json_date 变量......我需要每 30 秒更换一次倒计时方法中的 Time.now......关于如何实现这一点的任何想法

最佳答案

jQuery-countdown-Timer 插件不支持设置任意剩余时间。

此外,该插件不会将 remaining 作为选项。 (它也没有 display_on_complete 或 hide_on_complete` 选项。如果您链接到错误的插件,请告诉我。)

假设您希望插件具有任意剩余时间是您的顾虑,那么您必须修改插件。

我将 jquery.countdown-timer.js 的第 42~50 行更改为:

if (options.remaining) {
    seconds_remaining = options.remaining;
} else {
    // Split the specified date/time string into an array
    var date_elements = options.to.split(':');

    // Create Date objects for start and end date/times
    var end_date = new Date (date_elements[0], date_elements[1] - 1, date_elements[2], date_elements[3], date_elements[4]);
    var start_date = new Date();

    // Calculate number of seconds remain until end date/time
    seconds_remaining = (end_date.getTime() - start_date.getTime()) * .001;
}

并在您的 AJAX 调用中按照以下方式调用倒计时函数:

function refresh() {
    $j.ajax({
        type: "GET",
        url: "http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo&output=json",
        dataType: "json", // your url doesn't have a callback, no need for jsonp
        success: function(data){
            unix_timestamp = data.Result.Timestamp
            var json_date = new Date(unix_timestamp*1000);

            $j('#clock').countdown({ remaining: (event.start_date - json_date) * .001 });

            setTimeout(refresh, 30000);
        }
    });
}

这是假设 event 对象在 refresh 函数的范围内并且 $j 是您的 jQuery 对象。

我可能完全误解了你的问题,所以如果我是的话请告诉我。

关于javascript - 每 30 秒重置一次计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9595770/

相关文章:

javascript - 自动折叠可折叠 block

javascript - Jquery 设置计数器,但在调用函数时重置

javascript - 指定一个 Checkbox 来创建选定的行

javascript - jquery animate : two divs, 一个移出屏幕,另一个移入

javascript - Rails 辅助方法似乎正在杀死我的 JQuery 脚本

javascript - 韩语音节 PHP 或 JavaScript Romanizer(或任何其他替代方案?)

javascript - TypeError : clipBoard. createTextRange 不是函数

javascript 使用脚本点击按钮

ruby-on-rails - 将 Rails 中的主键更改为字符串

javascript - application.js 未加载到 Rails 应用程序;无法清除 tmp 存储。安全错误; Chrome