这是我写的代码。
function formatDate(date) {
var day;
if (date.getDate() < 10) {
day = "0" + date.getDate();
} else {
day = date.getDate();
}
var month;
var tempMonth = date.getMonth() + 1;
if ( tempMonth < 10){
month = "0" + tempMonth;
} else {
month = tempMonth;
}
var year = date.getFullYear();
return year + "-" + month + "-" + day;
}
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
jobDate = new Date(2016, 3, 7);
endDate = new Date(2016, 4, 1);
expireInterval = false;
timeoutVar = setTimeout(runJobFromJS,1000);
function runJobFromJS(){
var strDate = formatDate(jobDate);
console.log(strDate);
jobDate = jobDate.addDays(1);
if (jobDate >= endDate){
clearInterval(timeoutVar);
}
}
我原以为strDate
会打印从 4 月 7 日到 5 月 1 日的日期。但它只打印一次。为什么这setInterval
不能正常工作
您正在使用setTimeout
(在以毫秒为单位的时间后执行一次函数)而不是setInterval
(连续执行函数)。
的文档setInterval
:
WindowOrWorkerGlobalScope mixin 的 setInterval() 方法重复调用函数或执行代码片段,每次调用之间有固定的时间延迟。它返回一个唯一标识间隔的间隔 ID,因此您可以稍后通过调用 clearInterval() 将其删除。
的文档setTimeout
:
WindowOrWorkerGlobalScope mixin(以及 window.setTimeout 的后继者)的 setTimeout() 方法设置一个计时器,该计时器在计时器到期后执行一次函数或指定的代码段。
timeoutVar = setInterval(runJobFromJS,1000);//not setTimeout
function runJobFromJS(){
var strDate = formatDate(jobDate);
console.log(strDate);
jobDate = jobDate.addDays(1);
if (jobDate >= endDate){
clearInterval(timeoutVar);
}
}
演示:
function formatDate(date) {
var day;
if (date.getDate() < 10) {
day = "0" + date.getDate();
} else {
day = date.getDate();
}
var month;
var tempMonth = date.getMonth() + 1;
if ( tempMonth < 10){
month = "0" + tempMonth;
} else {
month = tempMonth;
}
var year = date.getFullYear();
return year + "-" + month + "-" + day;
}
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
jobDate = new Date(2016, 3, 7);
endDate = new Date(2016, 4, 1);
expireInterval = false;
timeoutVar = setInterval(runJobFromJS,1000);
function runJobFromJS(){
var strDate = formatDate(jobDate);
document.getElementById("result").textContent = strDate;
//console.log(strDate);
jobDate = jobDate.addDays(1);
if (jobDate >= endDate){
clearInterval(timeoutVar);
}
}
<span id="result"></span>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句