i的值应以5秒为间隔增加到500。但我需要将前一天的总数添加到第二天。为简单起见,我只需要在i的每日递增开始之前添加最大值。但是我正在初始化为0以进行递增,并且无论是否添加最大值都将重置。
最好的方法是什么? 到目前为止,这是我的代码。
<script type='text/javascript'>
var div = document.getElementById('count');
var i = 0;
var count = 0;
var max = 500;
var d = new Date();
// set d to midnight
d.setHours(0,0,0,0);
d.setMonth(0);
d.setDate(1);
d.setFullYear(2017);
var one_day=1000*60*60*24;
var today = new Date().getTime();
var numberofdays = Math.round((today - d.getTime()) / one_day);
function isPastMidnight() {
var currentTime = new Date().getTime();
if ((currentTime - d.getTime()) > 0) {
return true;
} else {
return false;
}
}
function updateCount() {
var currentTime = new Date().getTime();
if (!isPastMidnight()) {
document.getElementById('count').innerHTML = "Check back January 1, 2017.";
}
if (isPastMidnight()) {
if (numberofdays > 0 && today == d.getHours) {
addmax();
}
}
if (isPastMidnight() && i < max) {
i = Math.floor((currentTime - d.getTime() ) / 5000);
if (i > max) i = max;
document.getElementById('count').innerHTML = i;
}
if (i >= max) {
// Stop executing myself ("interval" is declared in global scope, so accessible from here)
clearInterval(interval);
}
}
updateCount();
var interval = setInterval(updateCount, 1000);
</script>
答案 0 :(得分:0)
您需要计算从1月1日开始的数量并乘以500,然后将5秒(或其他)的数量增加到500并将其添加到计数中。关于如何计算日期之间的天数以及对当前时间值进行数学计算,存在许多问题。
您的代码似乎过于复杂,如果您不想在2017年1月1日之前启动计数器,那么只需测试该日期是否在此之前。
/* Return number of whole days between dates. Sets
** time to 00:00:00 so only measures whole days.
** @param {Date} d0 - start date
** @param {Date} d1 - end date
** @returns {number} whole days between dates
*/
function daysBetweenDates(startDate, endDate) {
var d0 = new Date(+startDate);
var d1 = new Date(+endDate);
return Math.round((d1.setHours(0,0,0,0) - d0.setHours(0,0,0,0)) / 8.64e7);
}
/* Return a value that is 500 * the number of days since 1 Jan of the current year
** + 1 for each interval since 00:00:00 on the current day
** @param {Date} date
** @returns {number}
*/
function getCurrentCount(date) {
// Don't run before 1 Jan 2017
if (date < new Date(2017,0,1)) return 'Too early...';
// Get count for whole days since 1 Jan 2017
var count = 500 * daysBetweenDates(new Date(date.getFullYear(), 0), date);
// Find milliseconds since midnight at start of day
var dayPart = date - new Date(date).setHours(0,0,0,0)
// Add increments
var increment = 5000;
dayPart = Math.floor(dayPart % 8.64e7 / increment);
// Increment by dayPart if less than 500, or 500 otherwise
count += dayPart > 500? 500 : dayPart;
return count;
}
// Some tests
[new Date(), // Now
new Date(2017,0,1,0,30), // 2017-01-01 00:30:00
new Date(2017,5,23,0,30) // 2017-06-23 00:30:00
].forEach(function(d) {
console.log('Count for ' + d.toString() + 'is: ' + getCurrentCount(d));
});
&#13;
答案 1 :(得分:0)
乘以max变量的天数,并在数学语句中将其添加到i。所以第一天从0开始递增而不是500,我将它放入if语句中,只有当天数大于0时才允许它执行。 再次感谢!