gpt4 book ai didi

Javascript 时钟,落后几分钟

转载 作者:行者123 更新时间:2023-12-02 16:31:37 25 4
gpt4 key购买 nike

我想做一个小测试,以测试我在远离 javascript 太久之后的技能。试图成为真正的cwleaver并创建一个时钟对象,听起来很简单。我成功地创建了时钟等,没有遇到任何问题,但在大约 20 分钟后运行脚本后,我注意到我的时钟晚了几分钟!不知道我做了什么。

这只是一个小小的爱好项目,我根本没有从中获益。接受任何批评:)

function clock24(element){
this.date=new Date;
this.seconds=this.date.getSeconds();
this.minutes=this.date.getMinutes();
this.hours=this.date.getHours();
this.ele=element;
this.output={seconds:"00",minutes:"00",hours:"00"};
this.update();
var self=this;
this.ele.html(this.output['hours']+":"+this.output['minutes']+":"+this.output['seconds']);
this.increment=setInterval(function(){
self.seconds++;
if(self.seconds==60){
self.seconds=0;
self.minutes++;
}
if(self.minutes==60){
self.minutes=0;
self.hours++;
}
if(self.hours==24){
self.hours=0;
}
self.update();
self.ele.html(self.output['hours']+":"+self.output['minutes']+":"+self.output['seconds']);
},1000);
}
clock24.prototype={
constructor:clock24,
update:function(){
this.output['seconds']=(this.seconds<10)?"0"+this.seconds.toString():this.seconds.toString();
this.output['minutes']=(this.minutes<10)?"0"+this.minutes.toString():this.minutes.toString();
this.output['hours']=(self.hours<10)?"0"+this.hours.toString():this.hours.toString();
}
}

我的猜测是,脚本中的某些内容需要很长时间才能计算,但几乎不引人注目?或者我构建脚本的方式?

我无法将手指放在上面,但是!我敢打赌这真的很愚蠢,我提前为我的愚蠢问题道歉 XD

最佳答案

我可能会这样做:

function clock24(el){

var started, interval, seconds, minutes, hours;

this.update = function(){

var time = new Date(new Date().getTime() - started);

seconds = time.getSeconds();
minutes = time.getMinutes();
hours = time.getHours();

var pretty = hours + ':' + minutes + ':' + seconds;

if(typeof jQuery !== 'undefined' && el instanceof jQuery)
el.html( pretty );
else
el.innerHTML = pretty;

return this;

}

this.start = function(){

started = new Date().getTime();

this.update();

interval = setInterval(this.update, 1000);

return this;

}

this.stop = function(){

clearInterval(interval);

return this;

}

return this;

}

var clock = clock24(document.body).start();
body {

font-family: Arial, Helvetica, sans-serif;
font-size: 2em;

}

各有各的道理!

关于Javascript 时钟,落后几分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28240931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com