Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

javascript - Timer using frameRate and frame counter reliable?

I'm using p5js to program an animation with a timer countdown. I set my timer up to be updated each frame within an object that is being animated by the draw() function in sketch. Because of this, setInterval() will not work for what I'm trying to do.

I thought I could use the frameRate and a frame counter to decide if a second has passed:

this.updateTimer = function(){
  this.framecounter++;
  if(this.framecounter > frameRate()){
    this.framecounter = 0;
    //increment seconds
  }
}

Is this reliable? I tested it against an actual timer and it seems to be about 1 second ahead after about 15 seconds. Is there a better way to do this by calling a function each frame? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why don't you just use the frameCount variable? More info is available in the reference.

You could also use the millis() function instead. Again, the reference is your best friend.

If you still can't get it working, please post a MCVE (or better yet, a CodePen or JSFiddle) that we can run to see the problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...