如何在计时结束时重新启动计时器?

时间:2015-04-18 09:22:59

标签: javascript date timer

大家好!在我使用this timer的网站上,但我不明白它结束时我需要做什么。当计时器结束时,它应该在接下来的14天内重新启动。 你可以建议一些书籍,我可以在那里读到我的问题,或者只是在js中读到日期()。 谢谢!

1 个答案:

答案 0 :(得分:1)

这个插件有一个回调选项,一旦你的计时器结束就会被调用:

$('#countdown').timeTo({
    timeTo: new Date(new Date('Sat Apr 25 2015 09:00:00 GMT+0200')),
    displayDays: 2,
    theme: "black",
    displayCaptions: true,
    fontSize: 48,
    captionSize: 14,
    // important part
    callback: function(){ 
      alert('Timer ended'); 
    }
});

如果您想跟踪用户的出现时间localStorage,可以使用API​​来完成此操作。

开始计时器到期:

使用localStorage创建一个跟踪用户过期日期的功能。此功能返回用户第一次访问您网站时的开始日期。此日期用于确定用户是否已将过期时间延长至14天,但更多详细信息如下所示:

function handleUserDate(expireInDays){

  var now = new Date();
  var startDate = localStorage.getItem('timerStartDate');

  // has user already visited your site?
  if(startDate){

    // is user'date expired?
    startDate = new Date(Number(startDate));
    var futureDate = new Date(startDate.getTime()+expireInDays*(1000*60*60*24));
    if(now.getTime() < futureDate.getTime()){ 
      console.log('in future');
      return startDate;
    }

  }
  console.log('in past');
  localStorage.setItem('timerStartDate', now.getTime());
  return now;

}

下一个功能用于激活计时器并将剩余的天数放入 timeTo 选项中:

function startTimer(inDays){

   var now = new Date();
   var futureDate = new Date(now.getTime()+inDays*(1000*60*60*24));
   console.log(futureDate);

   $('#countdown').timeTo({
        timeTo: futureDate,
        displayDays: 2,
        theme: "black",
        displayCaptions: true,
        fontSize: 48,
        captionSize: 14,
        callback: function(){ 
          alert('Timer ended'); 
          var daysInFuture = 14;
          startTimer(daysInFuture);
        }
   });
}

计算开始日期到现在之间天数的时差的函数:

function getTimeDiff(date, date2, diff){
    return Math.abs(date.getTime()-date2.getTime())/diff;
}

把它们放在一起:

var expireinDays = 14;// 14 day max

var startDate = handleUserDate(expireinDays);
console.log(startDate);// returns date of the very first time or when already expired it returns current date
var now = new Date();
var dayInMill = 1000*60*60*24;

var dayDifference = getTimeDiff(startDate,now,dayInMill);
dayDifference = expireinDays - dayDifference; 
console.log(dayDifference); // days left

startTimer(dayDifference); // show timer