Timer using frameRate and frame counter reliable? - javascript

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!

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.

Related

How to sleep a certain amount of seconds in the Phaser-Framework

In my game i'm trying to make a variable go up gradually, so i need to be able to sleep a certain amount of time before I increment the variable again.
1) Use a timer. This will allow you to execute one off delayed events, or execute that function call repeatedly.
An example, as the phaser website basically gives you examples of everything if you search for it,
http://phaser.io/examples/v2/time/basic-timed-event
Also, from the docs
http://phaser.io/docs/2.4.8/Phaser.Timer.html
Should you need to repeat, note the function "loop" (I would post the link, but i don't have enough reputation yet).
2) The alternative is simply to tie in to Phaser's game tick. Within your state (if this is where you are executing you variable incrementation), create an update function (this will be called every game update). You can access time since last update.
Look up the class Phaser.Timer (again, i cannot post the link).
See the properties elapsed and elapsedMS. You could use this to manually track time elapsed since your last incremental event (behind the scenes, this is basically what phaser tweens or timed events are doing).
eg:
var timeSinceLastIncrement = 0;
function update()
{
// Update the variable that tracks total time elapsed
timeSinceLastIncrement += game.time.elapsed;
if (timeSinceLastIncrement >= 10) // eg, update every 10 seconds
{
timeSinceLastIncreemnt = 0;
// Do your timed code here.
}
}
Note, that option 1 is cleaner, and likely to be the preferred solution. I present option 2 simply to suggest how this can be done manually (and in fact, how it is generally done in frameworks like phaser behind the scenes).

requestAnimationFrame calling at more than 60FPS

I'm making a simple game and I'm having a problem where after minimizing the window for a few seconds, upon return the game runs at twice the framerate, and even more after that, adding 60 each time. My game loop looks like this:
function disp(){
update();
draw();
requestAnimationFrame(disp);
}
requestAnimationFrame(disp);
With both update and draw not including requestAnimationFrame. I have tried this on both firefox and chrome with the same results. Any ideas why this is happening? I've used this same method tons of times and this is the first time this has ever happened.
EDIT: You can find a fiddle of it at http://jsfiddle.net/5ttGs/
It's really simple so far as this kinda paused my progress. Click it a couple times and enjoy 10000+FPS gameplay
Fixed the problem with the help of cocco. Basically the onclick event called the disp function every time the canvas was clicked. Because the disp function had a requestAnimationFrame frame in it, it called it twice as much every second, resulting in the influx of frames. In order to fix I simply got rid of the disp in
canvas.addEventListener
function mouse_up() {
var matches = 0;
var overlap = 69;
mouse.up = false;
console.log("clicked", mouse.x,mouse.y);
disp();
}
You can find the result here: http://jsfiddle.net/5ttGs/

setTimeout with shorter timeout vs longer timeout

I am trying to debate whether this is a good method of handling timers in Javascript. I am using Angular, but the concept is the same as using setTimeout instead of the $timeout function Angular provides.
Old method:
$scope.timer=$scope.doTiming();
$scope.timeRemaining=30; //30 second timer;
$scope.doTiming=function(){
return $timeout(function(){
$scope.timeRemaining=$scope.timeRemaining-1;
if($scope.timeRemaining<=0){
$scope.disabledEntry=true;
$scope.submitData();
}else{
$scope.timer=$scope.doTiming();
}
},1000);
};
Time elapsed on a 30 timer: 30.050 seconds
New Method:
var startTime=new Date().getTime, delta; //new: get current time
$scope.timeRemaining=30;
$scope.timer=$scope.doTiming();
$scope.doTiming=function(){
return $timeout(function(){
delta=(new Date().getTime())-startTime; //new: get delta from start time
$scope.timeRemaining=$scope.timeRemaining-(delta/1000); //new: subtract by delta
if($scope.timeRemaining<=0){
$scope.disabledEntry=true;
$scope.submitData();
}else{
$scope.timer=$scope.doTiming();
}
},1);
};
Time elapsed on a 30 timer: 30.002 seconds
Major difference is that the old way looped every second, and ticked down the timer. The new way loops constantly very quickly and measures the time based on the change in time from the start, so it has the potential to be more accurate. I am wondering if this is reasonable or not? Is this type of instant loop going to cause issues on older computers? Should I maybe use the new way with a timer of 100 instead of 1? Thoughts?
EDIT
The new way is preferable to me for reasons associated with slowed timeouts: Chrome: timeouts/interval suspended in background tabs?
In my opinion, you should do as many "timeouts" as necessary, but as few as possible. In other words, if you need to update a timer every second, trigger a timeout every second. Nobody will be able to notice a 50ms delay in a timer update (nor would anyone care), so I think it is not worth bothering the browser with additional JavaScript cycles which, for example. might be better spent updating some animation.
I can't think of a reason why this wouldn't apply to the delta-time approach as well. Worst-case scenario would be that a tab goes to the background right after a one second timeout was triggered. When the user comes back to the tab, it would then take about a second until the timer would refresh, and in that interval the user would still see the timer value from when he made the tab inactive. If that is acceptable for your use case, I wouldn't worry about increasing the interval at all :)

Making a count-up with JavaScript

I'm trying to make a count up animation in Javascript. That is to say, the animation would start at 0, then, given an animation duration, count up to a given number. Is this possible in Javascript?
Additionally, is it possible to have the animation play only once the user scrolls down to that point on the page?
(function (e) {
setTimeout(function () {
e += 1;
}, 1000).call(this, 0);
It counts, after all?
Have you tried taking a look at the setInterval(func, delay[, param1, param2, ...]) method?
From Mozilla Developer Network:
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
See: https://developer.mozilla.org/en-US/docs/DOM/window.setInterval?redirectlocale=en-US&redirectslug=window.setInterval
To illustrate how to use the setInterval method to create a simple counter that starts counting at 0 and increments every second, I have created this jsFiddle: http://jsfiddle.net/zrccC/ - the sample also illustrates how to clear the timer.

Getting certain frequency with setInterval method

In a javascript code I develop, some function should be called every 1 second. But to be sure that this operation takes place every 1 second, the following code is utilized:
setInterval(doIt, 500);
function doIt() {
var now = (new Date()).getTime();
if(lastUpdate + 1000 >= now) {
/// code...
lastUpdate = now;
}
}
As far as I know setInterval(doIt, 1000) doesn't always mean that it's called every one second.
Is the above solution is a valid one? If not, what do you recommend?
You could use setTimeout instead of setInterval, and make dynamic adjustments each time your function is called. The idea is to set the timeout for a number of milliseconds sufficient to carry you to the next second boundary.
function timeoutFunc() {
// do interesting things
var time = new Date().getTime();
setTimeout(timeoutFunc, 1000 - time % 1000);
}
You'd start it off with:
setTimeout(timeoutFunc, 1000 - new Date().getTime() % 1000);
Synchronizing with the server seems like a bad idea, because you have no way of knowing whether the client clock is synchronized to anything (like the NTP server network). If it's not, then you server synchronizations are going to make things look wrong at the client, because the client clock will always be what seems right.
well setInterval IS defined in milliseconds. so it means its called every X millisdconds.
however the system can freeze or something like that!
but theres no practical better solution, you approach is fine.
if you really have an extensive javascript client application the results could stretch a little bit.
a possible solution for that is to get the system time and have a counter in your function. then ever X executions you align with the system clock, calculate how many function calls you should have until now and speed up the interval or slow it down.
this is as far as you can get to perfection. but it will be only a matter of milliseconds and probably not worth the effort.
may i ask what you are developing?

Categories

Resources