问题
basically I have written a function:
function animation(){
setTimeout(
function(){
requestAnimationFrame(animation);
if (player.currentFrame == player.frames) {
player.currentFrame = 0;
} else {
player.currentFrame++;
}
}
, 1000 / 15);
}
and I'm trying to call it with this code
animation(fps);
I tried making it like this:
function animation(fps){
setTimeout(
function(){
requestAnimationFrame(animation);
if (player.currentFrame == player.frames) {
player.currentFrame = 0;
} else {
player.currentFrame++;
}
}
, 1000 / fps);
}
and tried to call it with animation(30)
but it didn't work. I tried search topic like this but non of them is excatly what I want.
Any help would be appreciated! :)
回答1:
setTimeout will only call the function once after the time has elapsed, so unless you call animation again with fps, it will simply run once and be done. You could use setInterval to call the function every 1000/fps milliseconds.
var frame = 0;
animation(20);
function animation(fps){
console.log(fps)
setInterval(
function(){
console.log("A");
document.getElementById("sp1").innerHTML = frame;
frame++;
}
, 1000 / fps);
}
Sample fiddle: http://jsfiddle.net/Up4Cq/
Or if you want to use setTimeout, you need to call the animation function again:
function animation(fps){
console.log(fps)
setTimeout(
function(){
console.log("A");
document.getElementById("sp1").innerHTML = frame;
frame++;
animation(fps);
}
, 1000 / fps);
}
Here is the fiddle for setTimeout: http://jsfiddle.net/Up4Cq/1/
回答2:
Did you tried this syntax
function animation(fbs){
requestAnimationFrame(animation);
if (player.currentFrame == player.frames) {
player.currentFrame = 0;
} else {
player.currentFrame++;
}
setTimeout(function(){animation(fbs) }, 1000 / fbs);
}
I changed the code from setTimeout('animation(fbs)', 1000 / fbs); to setTimeout(function(){animation(fbs) }, 1000 / fbs);
来源:https://stackoverflow.com/questions/15810808/calling-a-function-inside-settimeout-and-inside-a-function