Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/454.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 窃听getDate函数_Javascript_Gettime - Fatal编程技术网

Javascript 窃听getDate函数

Javascript 窃听getDate函数,javascript,gettime,Javascript,Gettime,为什么我的getDate函数有时会出现错误,而我在控制台中会得到双重响应 这是我的密码 function getDate() { var newDate = new Date(); var year = newDate.getFullYear(); var month = newDate.getMonth()+1; var day = newDate.getDate(); var hours = newDate.getHours(); var m

为什么我的getDate函数有时会出现错误,而我在控制台中会得到双重响应

这是我的密码

function getDate() {
    var newDate = new Date();
    var year = newDate.getFullYear();
    var month = newDate.getMonth()+1;
    var day = newDate.getDate();
    var hours = newDate.getHours();
    var minutes = newDate.getMinutes();
    var seconds = newDate.getSeconds();
    if (month < 10) {
        month = "0"+month;
    }
    if (day < 10) {
        day = "0"+day;
    }
    if (hours < 10) {
        hours = "0"+hours;
    }
    if (minutes < 10) {
        minutes = "0"+minutes;
    }
    if (seconds < 10) {
        seconds = "0"+seconds;
    }
    return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
}
setInterval(function() {
    console.log(getDate())
},1000)
函数getDate(){ var newDate=新日期(); var year=newDate.getFullYear(); var month=newDate.getMonth()+1; var day=newDate.getDate(); var hours=newDate.getHours(); var minutes=newDate.getMinutes(); var seconds=newDate.getSeconds(); 如果(月<10){ 月份=“0”+月份; } 如果(第10天){ day=“0”+天; } 如果(小时<10){ 小时数=“0”+小时数; } 如果(分钟<10){ 分钟=“0”+分钟; } 如果(秒<10){ 秒=“0”+秒; } 返回年份+“-”+月份+“-”+天+“+小时+”:“+分钟+”:“+秒; } setInterval(函数(){ console.log(getDate()) },1000)
有几个原因。
setInterval
函数并不总是在1000毫秒后运行;毕竟,没有一个时钟是完美的。此外,在每1000毫秒等待之间,必须考虑程序的执行时间,这可能是几毫秒。至于重复时间,如果等待时间略少于一秒,或者JavaScript日期比实际计算机时间稍晚,则可能发生重复。底线是,平均每1000毫秒执行一次,加上实际函数的执行时间。

可能的重复