我创建了this clock,在暂停SPACE时应该暂停。但我的Js技能非常糟糕,所以我有点失落。时钟是1到5个时钟。这意味着每秒通过,5秒钟在时钟中通过。
var clock = new Clock("clock");
clock.start();
function Clock(id) {
var clock = this;
var timeout;
var time;
this.hours = 7;
this.minutes = 10;
this.seconds = 0;
this.stop = stop;
this.start = start;
var isStarted = true;
function Click () {
if (isStarted) {
stop();
}
else
{
start();
}
}
var element = document.getElementById(id);
function stop() {
clearTimeout(timeout);
}
function start() {
timeout = setTimeout(tick, 0);
time = Date.now();
}
function tick() {
time += 1000;
timeout = setTimeout(tick, time - Date.now());
display();
update();
}
function display() {
var hours = clock.hours;
var minutes = clock.minutes;
var seconds = clock.seconds;
hours = hours < 10 ? "0" + hours : "" + hours;
minutes = minutes < 10 ? "0" + minutes : "" + minutes;
seconds = seconds < 10 ? "0" + seconds : "" + seconds;
element.innerHTML = hours + ":" + minutes + ":" + seconds;
}
function update() {
var seconds = clock.seconds += 5;
if (seconds === 60) {
clock.seconds = 0;
var minutes = ++clock.minutes;
if (minutes === 60) {
clock.minutes = 0;
var hours = ++clock.hours;
if (hours === 24) clock.hours = 0;
}
}
}
}
答案 0 :(得分:0)
keypress
,这是最好的)keydown
和keyup
更新计时器/自动收报机,使其仅在未暂停时打勾:
var paused = false;
function tick() {
time += 1000;
timeout = setTimeout(tick, time - Date.now());
if ( !paused ) {
display();
update();
}
}
然后设置paused
标志:
document.onkeydown = function(e) {
if ( e.keyCode == 32 ) {
paused = true;
}
}
document.onkeyup = function(e) {
paused = true;
}
我不确定时间,因为您正在使用Date.now()
和setTimeout
,所以也许这会让它在onkeyup
之后跳转。我相信你能把这部分搞清楚。毕竟这是你的代码。
你的班级&#39;有一个非常奇怪的范围,因此tick
无法通过this
访问对象属性。示例显示了使用公共方法更改私有属性:http://jsfiddle.net/rudiedirkx/tej4pvm9/1/
如果你想创建一个类,你应该使用JS原型,因此this
可以工作,你不会为每个实例重新定义新的私有方法:http://jsfiddle.net/rudiedirkx/tej4pvm9/2/