为什么这个脚本不能正常工作(有时冻结)?
var period = 600;
function Boom(){
var timeBoom = window.setInterval(function() {
if (period > 300) {
period = 300;
setTimeout(function () {
period = 600;
}, 1000);
} else {
period = 600;
}
}, 5000);
}
function Shake() {
this.draw = function() {
setTimeout(function () {
Boom()
}, 5000)
};
}
我需要每5秒调用一次函数Boom()
,但变量应该在执行后再次更改(var period = 600)。
好了,伙计,基本上你需要摆脱所有联合国需要的计时的东西。
首先,简单说明一下:
setTimeout (func, x)
将在 x毫秒后执行函数func
setInterval (func, x)
将执行函数func 每 x毫秒。
所以你只需要设置一次interval,并让它工作。我已经更正了你的代码:
var period = 600;
function Boom() {
if (period != 300) {
period = 300;
} else {
period = 600;
}
}
function Shake() {
this.draw = function () {
var time = new Date().getTime();
var shakeX = (Math.sin(time * 2.0 * Math.PI / period) + 0);
this.x = shakeX;
var shakeY = (Math.sin(time * 2.0 * Math.PI / period) + 0);
this.y = shakeY;
this.context.drawImage(image, 0, 0);
this.context.translate(this.x, this.y);
setInterval(Boom, 5000)
};
}
John Resig——jQuery的创造者——有一篇关于javascript计时器的非常好的文章。
基本上,因为javascript是单线程的,setInterval
不能保证在每个间隔都触发——如果js引擎在一个特定的周期很忙,它会错过一个节拍。
setTimeout
将始终调用,但如果在时间到期时另一段代码已经排队,则可能会有额外的延迟——也就是说,等待时间可能比作为第二个参数传入的毫秒数要长。
我猜你的一些setTimeout
代码可能会妨碍setInterval
循环,但这只是一个猜测。
如果这是问题,请尝试命名您传递给setInterval
的匿名fn,然后将其传递给setTimeout
,等待5000毫秒,并在间隔到期时再次调用(递归)到同一函数。