在 javascript 中制作一个计时器?
Making a time counter in javascript?
我正在尝试制作一个简单的游戏,例如:www.aimbooster.com 来测试我的 javascript 知识,但我遇到了问题。基本上我想要一个计时器来计算用户获得的时间量,但我不能使用 setInterval 方法,因为程序必须等待一整秒才能发生任何其他事情,这不是我想要的。我想要的是这个在后台 运行 的计时器进程。我认为这通常被命名为 "Threading"。我该怎么做?我想要一些类似的东西:
function startTimer() {
while (stop == false) {
setInterval(function() {time++};1000);
}
}
function startGame() {
startTimer();
//MY GAME STARTS HERE
}
如果我现在这样做,startTimer 函数将持续运行,我将无法执行任何其他操作。我希望 startTimer 成为子进程,而主进程是游戏。
你可以这样做:
function startTimer() {
setInterval(function() {while (stop == false) time++}, 1000);
}
while (stop === false) {
setInterval(function() {time++};1000);
}
这是一个无限循环,您调用 setInterval 的时间是无限的,eventloop
没有机会将回调弹出到堆栈以增加时间变量。
我想保存定时器变量,用clearInterval停止定时器
function Game() {
}
Game.prototype.start = function() {
this.timer = setInterval(function() {
// do your stuff
}, 1000);
// start game
}
Game.prototype.stop = function() {
clearInterval(this.timer);
}
我正在尝试制作一个简单的游戏,例如:www.aimbooster.com 来测试我的 javascript 知识,但我遇到了问题。基本上我想要一个计时器来计算用户获得的时间量,但我不能使用 setInterval 方法,因为程序必须等待一整秒才能发生任何其他事情,这不是我想要的。我想要的是这个在后台 运行 的计时器进程。我认为这通常被命名为 "Threading"。我该怎么做?我想要一些类似的东西:
function startTimer() {
while (stop == false) {
setInterval(function() {time++};1000);
}
}
function startGame() {
startTimer();
//MY GAME STARTS HERE
}
如果我现在这样做,startTimer 函数将持续运行,我将无法执行任何其他操作。我希望 startTimer 成为子进程,而主进程是游戏。
你可以这样做:
function startTimer() {
setInterval(function() {while (stop == false) time++}, 1000);
}
while (stop === false) {
setInterval(function() {time++};1000);
}
这是一个无限循环,您调用 setInterval 的时间是无限的,eventloop
没有机会将回调弹出到堆栈以增加时间变量。
我想保存定时器变量,用clearInterval停止定时器
function Game() {
}
Game.prototype.start = function() {
this.timer = setInterval(function() {
// do your stuff
}, 1000);
// start game
}
Game.prototype.stop = function() {
clearInterval(this.timer);
}