gpt4 book ai didi

javascript - 使用 rAF.js 每秒运行 JavaScript 代码?

转载 作者:行者123 更新时间:2023-11-29 10:47:39 32 4
gpt4 key购买 nike

根据以下帖子,我从使用 setTimeout 改为使用 requestAnimationFrame: http://paulirish.com/2011/requestanimationframe-for-smart-animating/

如何将我的 animation() 循环中的一些代码设置为仅每秒执行一次?

我目前在做类似的事情:

animate() {
if(playGame) {
requestAnimFrame(animate);
}

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

if(time % 1000 <= 10) {
// code to run ~every second
}

// Also need to fix this, as it executes too fast, need to add score only
// every 100 milliseconds (player must stay in zone for 2 seconds to win)
if(playerInZone()) {
gameScore++;
if(gameScore >= 100) {
endGame();
}
} else {
gameScore = 0;
}

}

我不确定这样调用时间并执行取模是否是正确的方法?另外,我将以何种方式将我的 gameScore 代码更改为仅每(例如)200 毫秒触发一次?

注意:
我在 JavaScript 文件的顶部使用了这段代码:

window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();

但我还在我的文件中包含了 rAF.js,但不确定使用哪个:

// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating

// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel

// MIT license

(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}

if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};

if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());

最佳答案

当调用 requestAnimationFrame 时,“当前时间”以毫秒为单位发送,因此您可以这样做:

var lastTime = 0;

animate(currentTime) {
if (currentTime >= lastTime + 1000) {
// one second has passed, run some code here

lastTime = currentTime;
}


if(playGame) {
requestAnimationFrame(animate);
}
}

关于javascript - 使用 rAF.js 每秒运行 JavaScript 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16644142/

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