Timing events in javascript based on frames per second

Currently, I am working on a mini-game that requires some animations to be implemented in the form of frames per second. Here is my current approach:

var loadCount = 0;
var ticks = 15;


function loadingLoop() {
    loadCount++;
}

switch (loadCount) {
    case 1:
        $("#img").attr("src", "src/images/cenario/img004.png");
        break;
    case 2:
        $("#img").attr("src", "src/images/cenario/img005.png");
        break;
    case 3:
        $("#img").attr("src", "src/images/cenario/img006.png");
        break;
    // etc.... //
}

setInterval(function(){ 
    if (loadCount >= 6 && loadCount <= ticks){
        loadingLoop();
        if (loadCount === ticks) {
            clearInterval();
        }
        console.log(loadCount);
    }
}, 500);

I am interested in exploring more efficient ways to achieve the same goal. Any suggestions or recommendations would be greatly appreciated.

Answer №1

One way to optimize the code for image numbering is by utilizing the connection between the image load count and the naming convention. Instead of using a long switch statement, you can simplify it with the following code snippet:

$("#img").attr("src", "src/images/cenario/img" + (loadCount+3).toString().padStart(3, '0') + ".png");

The padStart method adds padding to the beginning of a string representation of a number. In this case, we are adding zeros to ensure a three-digit number.

In the timing function, one improvement could be saving the setInterval reference before attempting to clear it. Consider revising the code as follows:

let interval = setInterval(function(){ 
    if (loadCount >= 6 && loadCount <= ticks){
        loadingLoop();
        if (loadCount === ticks) {
            clearInterval(interval);
        }
        console.log(loadCount);
    }

}, 500);

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

Guide to Subscribing to a nested observable with mergeMap within a button's click event

The issue arises in the "addToWishlist" function as I attempt to concatenate the result of the outer observable with the inner observable array and then call the next method on the inner observable. The "addToWishlist" method is triggered by the click ha ...

Is it feasible to have unique popups for individual textbox edits?

I am experiencing a problem with a popup in Asp.net while using AJAX modalpopup extender. I am wondering if it is feasible to display one type of popup when the user modifies certain textboxes, and another type of popup for the remaining textboxes. I beli ...

TS4060: The export function's return type refers to a private name 'class' which is being used

I'm facing an issue here. Typescript keeps throwing this error: TS4060: Return type of exported function has or is using private name 'class' Student test.ts export default function EXPORTMODULE(GreetingText:string) { class Stud ...

Expanding the size of your Bootstrap 3 input box

https://i.sstatic.net/h7HpX.png Incorporating Bootstrap 3 into a Flask application, I have created a basic layout so far: <div class="container"> <div class="row"> <div class="col-xs-12"> <div class="content"> ...

Disabling a button following a POST request

Is there a way to prevent multiple clicks on a button after a post request is made? I want the button to be disabled as soon as it is clicked, before the post request is executed. Below is an example of my code where the button is supposed to be disabled w ...

In JavaScript, how to exit a loop within the success callback of an AJAX call

I am faced with a task of sending an $.ajax request and then examining the response HTML for specific text. If the desired text is found, I need to trigger a separate function and halt the current loop to prevent continuous requests for the remaining items ...

The gaps separating rows

I'm struggling with getting my divs to look like a table, especially when it comes to highlighting a selected row. I've tried adjusting padding and margins without success. Does anyone have any suggestions on how I can achieve this effect? .ta ...

Tips on utilizing createBrowserRouter within react along with react router-dom

Within my application, I am utilizing the BrowserRouter component to handle the rendering of routes and components. However, I am interested in incorporating a loader functionality, which is proving challenging with my current approach. <BrowserRouter&g ...

Is it possible to duplicate the mesh thousands of times and animate it without causing significant performance issues

I have created a demo with numerous cubes that share the same geometry and texture: texture = THREE.ImageUtils.loadTexture ... material = new THREE.MeshLambertMaterial( map: texture ) geometry = new THREE.BoxGeometry( 1, 1, 1 ) cubes = [] for i in [0..1 ...

I encountered an issue trying to insert a PHP variable within a CSS style tag that I had written in an echo statement

I was struggling to achieve the desired outcome. Can anyone advise me on how to insert a PHP variable into a style tag that is within an echo statement? <div class="container"> <h2>Grantt chart for given process</h2> <divclass ...

unable to locate the XPath for the anchor element nested within a span element

Having mastered the use of xpath, I am facing a challenge with the following link - . Can someone guide me on how to locate the xpath for the "Demo" hyperlink on this site? I attempted using //a[text()= 'Demo '] but please conside ...

Guide on incorporating external JavaScript and swiper.js files into Nuxt 3 (nuxt.config.ts)

I encountered an issue when trying to include an external JavaScript file in nuxt.config.ts for Nuxt 3. Despite the CSS files working correctly, the script files failed to load properly. After conducting extensive research, I was unable to find a solution ...

What are the reasons for passing a global variable to a function?

Is there a difference between the two ways of writing this code? First Method: (function(i) { // Manipulate i here }(global_variable)) Second Method: (function() { // Manipulate global_variable here }()) What's the reason for passing a gl ...

Authenticating Users with HTML in Django

I am experiencing an issue with the following condition: {% if object.author == user or object.res_person_1_username == user %} When I display variables using code like this: <p class="article-content mb-1"><strong>object.res_person_ ...

How to create an array of objects in TypeScript

I am looking to define an array of objects in TypeScript. Here is my example: const a = [{ name: 1, age: 2, car1: 8, car2: 8, car3: 8, name4: 1, age4: 2, car41: 8, car42: 8, car34: 8, }, { name: 1, age: 2, car1: 8, car2: 8, ...

Send the fullcalendar event objects array to the backend

Struggling to send fullcalendar events to my Django backend, I noticed that AJAX is not transmitting the correct data. Any advice on how to properly transfer these events to the backend? $.ajax({ url: '/home/update_event/', method: 'POST ...

What is the best way to incorporate visual indicators into specific columns containing certain keywords?

Is there a way to customize the script code responsible for displaying table data so that icons automatically appear next to specific keywords in the Gender column? For instance, can we have an icon like glyphicon glyphicon-heart-empty for Male and glyphic ...

"Encountering an Internal Server Error while trying to submit the

Seeking Assistance: I am experiencing an error when attempting to send a contact form. https://i.sstatic.net/7sK58.jpg The Visual Basic code causing the issue: <% mail_to = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=" ...

Automatically populate the checkbox with the specified URL

Is it possible to pre-fill a checkbox in an HTML form using the URL? For example, if we have a URL like www.example.com/?itemname=sth Would there be a similar method to pre-select a checkbox via the URL? <ul class="list-group"> <li c ...

The issue is that dates submitted from jQuery are not being captured in the POST variable in

I'm currently in the process of integrating fullcalendar into my php application. However, I've encountered an issue when trying to save events to the database - specifically, the database only accepts title and url if they are enclosed in doubl ...