What strategies can be used to reduce the frequency of update calls?

I'm currently working on a Tetris demo using ThreeJs. To render the game, I am utilizing requestAnimationFrame. Below is a snippet of the code:

game.prototype.render = function(){
var thisObj = this;

requestAnimationFrame( function() {thisObj.render();} );

var now = new Date().getTime();
var dt = now - (time || now);
time = now;

this.update(dt);

this.boardMgr.render(dt);
this.renderer.render(this.scene, this.camera);
};

this.update(dt) - invokes boardMgr.update(dt)

BoardMgr.prototype.update = function(dt) {
if(this.activeBlock == null){
this.activeBlock = this.getNextBlock();
//console.log("letter: " + this.activeBlock.letter);
}

// update active block based on keyboard input
// left/right/falldown
// otherwise
{
this.move(this.activeBlock, DIRECTION.DOWN);
}
};

When testing the demo, I noticed that the blocks fall too quickly. It seems like the update function is being called too frequently, causing the blocks to update rapidly. How can I regulate the speed at which the blocks fall? Should I reduce the frequency of update calls? What is the optimal way to address this issue?

You can view the full code here: https://github.com/brainydexter/PublicCode/tree/master/graphics

Movement: The game features a 5x5 grid-board, where each block has a specific board position. When a block can move downwards, its new position is calculated as: (x, y+1). During rendering, the block's position in the world coordinate system is updated based on the board position. Hence, blocks move in increments of BLOCK_WIDTH:

BoardMgr.prototype.render = function(dt) {
for (var i = 0; i < this.blocks.length; i++) {
if(this.blocks[i].visible)
{
this.blocks[i].position.x = (this.BLOCK_WIDTH/2) + ( this.blocks[i].boardPosition.x * this.BLOCK_WIDTH);
this.blocks[i].position.y = (this.BLOCK_WIDTH/2) + ( this.blocks[i].boardPosition.y * this.BLOCK_WIDTH);
}
};
};

Answer №1

UPDATE

It seems like you're aiming for the blocks to snap to a grid and have that classic jerky movement down the screen. The simplest approach to achieve this is by tracking the time since the last update and only moving the blocks again when this exceeds a certain threshold, such as 500 milliseconds.

// Time intervals for each movement
sidestep = 240;
downstep = 500;
fallstep = 80;

BoardMgr.prototype.update = function(dt) {
    this.vtimer += dt;
    this.htimer += dt;
    ...

    if ( left && this.htimer > sidestep ) {
        this.move(this.activeBlock, DIRECTION.LEFT);
        this.htimer = 0;
    }
    if ( right && this.htimer > sidestep ) {
        this.move(this.activeBlock, DIRECTION.RIGHT);
        this.htimer = 0;
    }

    if ( ( fall && this.vtimer > fallstep ) || ( this.vtimer > downstep ) ) {
        this.vtimer = 0;
        this.move(this.activeBlock, DIRECTION.DOWN);
}
};

If you prefer the movement to be more responsive to left and right inputs without a limit on sideways speed, you can make the following adjustments:

BoardMgr.prototype.update = function(dt) {
    this.vtimer += dt;
    ...

    if ( left )
        this.move(this.activeBlock, DIRECTION.LEFT);
    if ( right )
        this.move(this.activeBlock, DIRECTION.RIGHT);

    if ( ( fall && this.vtimer > fallstep ) || ( this.vtimer > downstep ) ) {
        this.vtimer = 0;
        this.move(this.activeBlock, DIRECTION.DOWN);
}
};

Answer №2

Typically, when working with the boardManager.update function, it's important to adjust the activity based on the time elapsed since the last run. It seems like you already have a good handle on this.

For more information on game loops, you may want to explore some general topics at

In essence, the frequency of calling update does not necessarily need to change; rather, it's crucial to adapt your actions based on the update rate.

Additionally, when considering rendering, it may not be essential to factor in the time delta. The main objective is to depict the current state post update that aligns with the desired smoothness of movement.

For instance, when implementing gravity in block movement within the update function, you might need to calculate the distance a block should drop per millisecond based on the time delta. This calculation can influence the movement to achieve the intended effect.

While user inputs like shifting a block sideways may not require time delta consideration, you could incorporate movement rendering in the rendering process to enhance smoothness. Alternatively, immediate block position updates could suffice in certain scenarios.

Ultimately, the decisions regarding aesthetics, behavior, and difficulty levels boil down to your preferences. Luckily, you have the necessary parameters to fine-tune these aspects according to your preferences.

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

What could be causing the Angular router outlet to not route properly?

Check out this demo showcasing 2 outlets (Defined in app.module.ts): <router-outlet></router-outlet> <router-outlet name="b"></router-outlet> The specified routes are: const routes: Routes = [ { path: 'a', com ...

To ensure that new tabs are opened directly within jQuery UI tabs, the tab should be created within the jQuery UI tabs interface

I have integrated jquery-UI to create a dynamic Tab panel. When I click on the "Add Tab" button, a new tab is created. However, the new tab does not open automatically. It only opens when clicked on. $(function() { var tabTitle = $( ...

The functionality of event bubbling appears to be ineffective while utilizing a bootstrap modal in an AngularJS application

I have a question regarding the use of Bootstrap modal. To begin with, I apologize for any issues in understanding my question due to my English skills. I have created a button as a directive to dynamically add, with reference to the following links. . ...

Use jQuery to populate a span element with information that is solely obtainable within a foreach loop during the rendering of buttons

I am currently navigating through learning MVC, and I have hit a roadblock. Working with Web Forms was more familiar to me, so I find myself struggling quite a bit with this new framework. After dedicating most of my day to it, I realize I need some assist ...

Embed fashion and graph elements into a CSV document (generated from <script>)

Encountering an issue with my code. I am looking to export an HTML table to a CSV file (specifically Libre Office Calc, regardless of csv, xls or xlsx format, as long as it runs on a Linux Server). Found a script online that works well after some modificat ...

What is the process for showcasing specific data using Vue.js?

{ "status": "ok", "source": "n", "sortBy": "top", "articles": [ { "author": "Bradford ", "title": "friends.", "url": "http: //", "urlToImage": "http://" }, { ...

AngularJS extension known as 'ngclipboard'

I've been attempting to utilize a plugin called ngclipboard in Angular, but something seems amiss as it's not functioning as expected. There are no error messages, however, the text from the input box is not being copied to the clipboard. To see ...

What is the method for including a placeholder with sequential numbering?

When I click on the "Add String" button, it clones the first table row with an input in the table and adds it to the table. I also need to add a +1 number in the placeholder of the copied element. How can I determine the last placeholder before copying and ...

Sending auth0 token as a parameter in $http.get request in Angular

I am encountering difficulties when trying to attach the auth0 token to a http.get request for an API that requires the token. The token is generated upon user login and stored in the browser's local storage, which is functioning properly. The challen ...

Calculating the hour difference between two time stamps (HH:MM:SS a) using moment.js

I have two time without date var startTime="12:16:59 am"; var endTime="06:12:07 pm"; I need to calculate the total hours between the above times using a library like moment.js. If it's not achievable with moment.js, then please provide a solution u ...

The process of saving report filters and making them accessible for both running and scheduling tasks

I am facing a use case where I need to add query parameters to API calls and save them for future use. Essentially, I have a report that requires multiple filters to be saved - some predefined and others customizable. These saved filters can then be execut ...

jQuery drag and drop for more than one object

I am in the process of building a web-based file browser using jQuery and PHP. One of the tasks I need to accomplish is the ability to select multiple files/folders and drag them into another folder. My research so far indicates that jQuery UI's drag ...

What is the best way to transfer information between two HTML pages using PHP?

While working on updating a record, I encountered an issue trying to pass the student's ID from one page to another without displaying it in the query string. Despite attempting to use window.location and AJAX for navigation between pages, I haven&apo ...

Is there a way to simultaneously modify several data variables within a Chart.js label?

I'm currently working on dynamically updating a line chart with two data entry points using the variable name "data." Take a look at the code snippet below: var lion = new Chart(ctx2, { type: "line", data: { labels: ["Apr", "May", ...

Enhancing website performance with a combination of Google Analytics outbound click tracking and a JavaScript speed bump

I have successfully integrated the universal GA for tracking outbound clicks, however I have also added a "speed bump" pop-up message that appears when a user clicks on an offsite link. The JavaScript code for this is as follows: (specific to bank client - ...

An error occurred while trying to access the stored data at https://localhost:5000. The SSL protocol encountered

I am attempting to utilize an API to retrieve data and transfer it to MongoDB from my React application to the Node.js server, but I keep encountering an error message along with another issue in the console. https://i.stack.imgur.com/Bj4M6.png Despite e ...

The completion event for Ajax and Json does not activate Google Maps

I'm currently facing an issue with my Google Maps functionality. Despite trying various solutions that involve hidden tabs, the problem persists. The trouble lies in the fact that my ajax function successfully posts and retrieves data, but fails to tr ...

"Troubleshooting Problems with Scaling in the jQuery Mouse Wheel Plugin

I am currently utilizing this code in conjunction with the following plugin: mouse wheel $('#painter').on('mousewheel', function(e) { cp.scale(2, 2); var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.de ...

Notify immediately if there is any clicking activity detected within a designated div container

I am looking to trigger an alert when a specific div is clicked. Here is the scenario: <div class="container"> <div class="header"> <h1>Headline<h1> </div> <div class="productbox"></div> </div> I have succ ...

Error: The function $.get is not recognized when using jQuery with babel-node

Currently, I am executing the code below from a test.js file using babel-node in the command line: babel-node test.js installation of jquery npm i --save jquery test.js: import $ from 'jquery'; $.get("www.google.com"); Upon execution, I en ...