Is there a way to call a function only once when a certain condition is met in Three.js? I am currently sampling the frames per second (FPS) to send it to an external service. The FPS is sampled and averaged over time, and the average value is sent after 10 samples have been collected.
This FPS calculation method is inspired by the Stats plugin for Three.js. However, I am facing an issue where the function sendInfo()
gets called multiple times, seemingly corresponding to the number of FPS values collected (e.g., if FPS = 55, it gets called 55 times).
How can I prevent this from happening and ensure that sendInfo()
is only called once?
Below is a snippet of my animate() loop: (some variables are declared outside)
function animate() {
requestAnimationFrame(animate, renderer.domElement);
var beginTime = performance.now();
// Additional computations, raycasting, etc.
renderer.render(scene, camera);
var endTime = performance.now();
frames ++;
if (endTime > prevTime + 1000) {
var fps = Math.round(frames * 1000 / (endTime - prevTime));
fpsLog.push(fps);
prevTime = endTime;
frames = 0;
}
// If enough FPS values have been collected, calculate the average and call the function
if (fpsLog.length === 10) {
var totalFps = 0;
for (var i = 0; i < fpsLog.length; i++) {
totalFps += fpsLog[i];
}
var averageFps = Math.ceil(totalFps / fpsLog.length);
sendInfo(averageFps);
}
}
I attempted to set a boolean flag after calling sendInfo()
and check it inside the conditional statement if (fpsLog.lenght === 10)
, but encountered the same issue.
if (fpsLog.length === 10 && isExecuted === false) {
var totalFps = 0;
for (var i = 0; i < fpsLog.length; i++) {
totalFps += fpsLog[i];
}
var averageFps = Math.ceil(totalFps / fpsLog.length);
sendInfo(averageFps);
isExecuted = true;
}