Tips for executing a function only once within the animation loop in Three.js

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;
    }

Answer №1

Moving the declaration of the variable isExecuted outside of the animate() loop was the solution to this problem.

Answer №2

Not sure if this will be useful, HOWEVER:

I previously had the following setup: onTransitionEnd: run a function = problematic, triggers every time there is an animation or transition

I switched it to: onAnimationEnd: run a function = resolved, now only triggers once

Despite my Div transitioning and resizing after onAnimationEnd, the function does not get triggered.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The button similar to Facebook does not function properly when using fancybox

My photo gallery uses fancybox, and when fancybox is open a like button appears outside the title. However, the Facebook like button doesn't seem to work. Here is my JavaScript code: $(".fancyboxi").fancybox({ padding: 0, openE ...

Remove a specific date entry from the database using VUE JS and Axios

I am encountering a challenge with Vuejs as I work on a To-Do list. The tasks need to be stored in a MySQL database, and I also want the ability to delete tasks. While I have succeeded in importing and creating data, I'm facing difficulty in deleting ...

Generate a new entry and its linked data simultaneously

The Issue: Picture this scenario: I have two connected models, Library which has multiple Books: var Library = sequelize.define('Library', { title: Sequelize.STRING, description: Sequelize.TEXT, address: Sequelize.STRING }); var Boo ...

IE11 blocking .click() function with access denied message

When attempting to trigger an auto click on the URL by invoking a .click() on an anchor tag, everything works as expected in most browsers except for Internet Explorer v11. Any assistance would be greatly appreciated. var strContent = "a,b,c\n1,2,3& ...

Is it possible to alter the css twice through the action of clicking on two individual buttons

One feature I have in my interface allows users to click on the edit button to bring up borders and change the background color of other divs. Once the edit button is pressed, it is replaced by cancel and save buttons. The goal is for the borders and backg ...

A step-by-step guide on transferring data from an HTML file to MongoDB using Python Flask

I am currently developing a web application that involves uploading multiple CSV files and transferring them to MongoDB. To build this application, I have utilized Python Flask. To test out different concepts for the application, I have created a sample f ...

Why is a dispatch call in React-Redux being executed before another?

My Pokedex is functioning properly, but I have encountered an issue with React-Redux Dev Tools: https://i.sstatic.net/F0Ifh.png The function "getPokemonsInfo" is being called before "getPokemonsUrls", however, "getPokemonsInfo" should only be triggered w ...

Guidelines for transferring JavaScript array data to a csv file on the client side

Despite the abundance of similar questions, I am determined to tackle this using JavaScript. Currently, I am utilizing Dojo 1.8 and have all attribute information stored in an array structured like this: [["name1", "city_name1", ...]["name2", "city_name2" ...

Custom div element obstructs information window on map due to lack of auto panning feature

I created a unique div that is absolutely positioned on a Google Map. You can view the image below to see it. My issue is that the info window is being covered by this custom div element, as demonstrated in the picture. https://i.stack.imgur.com/1TgyQ.jpg ...

Utilize the key as the value for options within an object iteration in Vue.js

I have an object called colors, which stores color names: { "RD": "Red", "BL": "Blue", "GR": "Green", "YW": "Yellow" } In my dropdown menu, I'm generating options for each color in the colors object: <select v-model="colors"> <op ...

Import a picture file into Photoshop and position it at a designated location

I need assistance with developing a function that can load an image and position it at specific x, y coordinates in Photoshop. Below is the code I have so far: var docRef = app.activeDocument; function MoveLayerTo(fLayer, fX, fY) { var Position = fLaye ...

Animate the Bootstrap carousel from top to bottom instead of the traditional left to right movement

Is there an option available in the bootstrap carousel to animate it from top to bottom and bottom to top, rather than from right to left and left to right? jsFiddle link <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval=" ...

*NgFor toggle visibility of specific item

Here is a snippet of HTML code that I'm working with: <!-- Toggle show hide --> <ng-container *ngFor="let plateValue of plateValues; let i=index"> <button (click)="toggle(plateValue)">{{i}}. {{ btnText }}</button> ...

Getting a product by its slug can be achieved with Next.js 14 and Sanity by utilizing the capabilities

My dilemma involves retrieving specific product details based on the current slug displayed in the browser. While I successfully retrieve all products using the following code: export async function getAllProducts() { const productData = await client.fe ...

jQuery is working perfectly on every single page, with the exception of just one

Check out my code snippet here: http://jsfiddle.net/9cnGC/11/ <div id="callus"> <div class="def">111-1111</div> <div class="num1">222-2222</div> <div class="num2">333-3333</div> <div class="num3">444-4444< ...

What is the best way to eliminate the final character from a series of repeated Xs and following strings

Data consists of [one][two][three]. I want to exclude the last set of brackets and have a result like [one][two]. How can this be achieved using jQuery? ...

Enhancing tooltips in a multi-series chart with Highcharts - incorporating suffixes

Apologies for my lack of experience once again. I am now looking to enhance my tooltip by adding a suffix to indicate % humidity and °C for temperature. While the code derived from ppotaczek with some tweaks is working well, I've been struggling to a ...

What are the reasons behind the jQuery file upload failing to work after the initial upload?

I am currently utilizing the jQuery File Upload plugin. To achieve this, I have hidden the file input and set it to activate upon clicking a separate button. You can view an example of this setup on this fiddle. Here is the HTML code snippet: <div> ...

What is the best way to utilize an Angular service method from a controller?

As a newcomer to Angular, I have created an 'Employee Search' Service module. Let's take a look at the code: // Employee Search Service app.service('employeeSearchService', function($http, resourceServerAddress){ this.empList ...

Instructions for adding and deleting input text boxes on an ASP.NET master page

*I am currently facing an issue with adding and removing input textboxes for a CV form using ASP.NET in a master page. Whenever I click on the icon, it doesn't seem to work as intended. The idea is to have a textbox and an icon "+" to add more textbox ...