jquery数组计时器倒计时

时间:2014-01-29 12:30:07

标签: javascript jquery arrays timer

我有这个 JSFiddle 有脚本来做多个计时器,但只有最后一个计时器工作,我搜索了很多关于这个,并没有找到答案。

我认为问题在于计时器阵列,但不确定,你能帮忙吗?

jQuery.fn.countdown = function (yr, mes, d, h, m, s) {
    $that = $(this);
var delta = 0;

var start = function (yr, mes, d, h, m, s) {
    theyear = yr;
    themonth = mes;
    theday = d;
    thehour = h;
    theminutes = m;
    theseconds = s;

    var today = new Date();
    var todayy = today.getYear();
    if (todayy < 1000) todayy += 1900;
    var todaym = today.getMonth();
    var todayd = today.getDate();
    var todayh = today.getHours();
    var todaymin = today.getMinutes();
    var todaysec = today.getSeconds();

    var todaystring = montharray[todaym] + " " + todayd + ", " + todayy + " " + todayh + ":" + todaymin + ":" + todaysec;

    var futurestring = montharray[mes - 1] + " " + d + ", " + yr + " " + thehour + ":" + theminutes + ":" + theseconds;

    dd = Date.parse(futurestring) - Date.parse(todaystring) + delta;

    dday = Math.floor(dd / (60 * 60 * 1000 * 24) * 1);
    dhour = Math.floor((dd % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1);
    dmin = Math.floor(((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1);
    dsec = Math.floor((((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1);

    if (dday < 0 && dhour < 0 && dmin < 0 && dsec < 1) {
        alert("ended");
        return;
    } else {
        $that.html("<span><strong>" + dday + "</strong><span> Days | " + "<span><strong>" + dhour + "</strong></span> Hours | " + "<span><strong>" + dmin + "</strong></span> Minutes");
    }

    setTimeout(function () {
        start(theyear, themonth, theday, thehour, theminutes, theseconds);
    }, 1000);
}
return {
    start: function () {
        start(yr, mes, d, h, m, s);
    },
    addTime: function (ms) {
        delta += ms;
    }
}

};

这是倒计时的原因。检查jsfiddle中的其余部分

1 个答案:

答案 0 :(得分:1)

问题是您在声明变量时忽略了var关键字,因此它们是declared as global并在计时器之间共享。这应该有效(jsfiddle):

var $that = $(this);

...

var theyear = yr;
var themonth = mes;
var theday = d;
var thehour = h;
var theminutes = m;
var theseconds = s;

...

var dd = Date.parse(futurestring) - Date.parse(todaystring) + delta;

var dday = Math.floor(dd / (60 * 60 * 1000 * 24) * 1);
var dhour = Math.floor((dd % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1);
var dmin = Math.floor(((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1);
var dsec = Math.floor((((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1);