Invoke a function at regular intervals using requestAnimationFrame

I'm currently working on a personal project using Three.js. In my code, I am utilizing the requestAnimationFrame function and trying to figure out how to call a specific function every 2 seconds. Despite my search efforts, I have been unable to find a satisfactory solution.

Here is a snippet of my code:

function render() {
   // Call the createNewObject() function every 2 seconds
   if(eachTwoSecond) {
      createNewObject();
   }
   requestAnimationFrame(render);
   renderer.render(scene, camera);
}

Any suggestions or ideas would be greatly appreciated!

Answer №1

requestAnimationFrame sends a single parameter to your callback function which represents the current time (in milliseconds) when requestAnimationFrame executes the callback. This can be utilized to determine the time interval between consecutive render() calls.

var last = 0; // timestamp of the last render() call
function render(now) {
    // invoke the createNewObject() function every 2 seconds
    if(!last || now - last >= 2*1000) {
        last = now;
        createNewObject();
    }
    requestAnimationFrame(render);
    renderer.render(scene, camera);
}

Answer №2

This script is designed to output sequential numbers every 2 seconds.

let lastNum = 0;
let currentNum = 0;
let intervalSpeed = 2;

function countNumbers(timestamp) {
  let timeInSeconds = timestamp / 1000;

  if (timeInSeconds - lastNum >= intervalSpeed) {
    lastNum = timeInSeconds;
    console.log(++currentNum);
  }

  requestAnimationFrame(countNumbers);
}

countNumbers();

Answer №3

Dealing with a similar issue led me to devise the following workaround:

let count = 0
const interval = 2 * 60 // assuming 60 ticks per second

function display() {
  if (++count % interval === 0)
    doSomethingElse()

  requestAnimationFrame(display)
}

UPDATE: This approach is tied to frame rate, making it less than ideal.

Answer №4

Utilizing the power of requestAnimationFrame, you can ensure a smooth 60fps frame rate (assuming your browser can handle it). By waiting for 2 seconds before requesting a new frame, the browser will deliver a frame right on cue:

        function render() {
            // Call createNewObject() every 2 seconds
            createNewObject();
            renderer.render(scene, camera);
        }

        setInterval(function () {
            requestAnimationFrame(render);
        }, 2000);

Answer №5

Effortless JavaScript Timer that executes every specified interval

Variation of the MDN Example --> Here.

/*
<div id="test">
        <h1>Hello World</h1>
</div>
*/
const element = document.getElementById('test');
let start, previousTimeStamp;


timerConfig = {
    frequency: 1, // Seconds
    stopAt: 10, // Seconds,
    pos: 1,  // px
    posStep: 10,  // px
    updatePos: () => {
        timerConfig.pos = timerConfig.pos + timerConfig.posStep;
    }
}

function customTimer(timestamp) {    
    if (start === undefined)  start = timestamp;
    if (previousTimeStamp === undefined)  previousTimeStamp = timestamp;
    const seconds = timerConfig.frequency*1000;
    const tick = timestamp - previousTimeStamp; 

    function performAction() {
        element.style.transform = 'translateX(' + timerConfig.pos + 'px)';
    }

    if (tick >= seconds) {
        performAction();
        previousTimeStamp = timestamp; // Updating The Timer every second
        timerConfig.updatePos();
    }
    if (timestamp < timerConfig.stopAt*1000) requestAnimationFrame(customTimer); // 10 Seconds    
    
}

requestAnimationFrame(customTimer);

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

Unable to modify the state with a computed setter in VueJS

In my Vue.js project, I am trying to work with a form where the end_saving value needs to be computed based on the values of start_saving and duration. To achieve this, I want to utilize the saving.end_saving property in the v-model for submission via a PO ...

Issues arise with loader path syntax when CDNs are not used. ThreeJs npm node js library requires relative references to begin with either "/", "./", or

Error: An Uncaught TypeError has occurred: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../". Despite reading multiple questions on this topic both in and out of SO, I'm still struggling to und ...

Vue.js: API request taking too long during mounted lifecycle

I am facing an issue with API data in my Vue js project. The page loads quickly but the data from the API takes more than 5 seconds to load. Strangely, the API response appears very fast in the console. I have implemented the API in a separate file called ...

TabContainer - streamline your selection process with inline tabs

I am currently working on a GUI that includes a TabContainer with two tabs, each containing a different datagrid. I initially created the tabcontainer divs and datagrids declaratively in HTML for simplicity, but I am open to changing this approach if it wo ...

Tips for ensuring only digits can be entered in a textbox on Firefox

Having trouble validating digits in a textbox on both IE 9 and Firefox versions 4 & 5. Does anyone know how to solve this issue? I've attempted the solutions provided in previous questions, but I'm still encountering problems. My goal is to only ...

Infinite scrolling with Jquery: Loading dynamic content seamlessly from external websites

Hey there! I recently started using this cool jQuery plugin called jquery-endless-scroll. Here's a snippet of my code: $(function() { $('#list').endlessScroll({ pagesToKeep: 10, fireOnce: false, insertBefore: "#list div:first ...

Transform the character encoding from a non-standard format to UTF-8

Imagine a scenario where there is a page with <meta charset="EUC-KR">, let's call it address-search.foo.com, that allows users to search for an address and sends the data to a specified URL by submitting an HTML form using the POST met ...

What is the correct way to incorporate a JavaScript file into a PHP document?

I'm encountering an issue with a js file in php. When I try including it like this: ?> <script type="text/javascript" href="file.js"></script> <?php The file is not being included and I receive an error stating that the function is ...

Update the nodes in a directed graph with fresh data

For the past few days, I've been facing a persistent issue that I just can't seem to find a solution for when it comes to updating nodes properly. Using three.js to render the graph adds an extra layer of complexity, as the information available ...

Develop a wrapper for API handlers to minimize redundancy

Currently, I find myself having to duplicate this code in every component whenever I need to call a private endpoint. This approach is messy, not sustainable, and prone to errors. How can I encapsulate this behavior within a function that I can place in ...

Steps for designing a popup modal that triggers upon calling a specific function

I'm facing some challenges while trying to develop a modal that pops up when a specific section of an image map is clicked. Here is the snippet from my HTML file: <head link rel="stylesheet" href="ryanspagecss.css"></hea ...

The issue of 'require is not defined' arises when using Webpack configuration including "target: 'node'" and "type: 'module'"

My webpack configuration for an express server that utilizes ES6 modules, includes "type": "module" in the package.json file, and has target: 'node' specified, fails with the error ReferenceError: require is not defined. Upon ...

Is it possible to apply CSS animations to manipulate HTML attributes?

I'm exploring how to animate an HTML element's attribute using CSS and looking for guidance. While I am aware that you can retrieve an attribute using the attr() CSS function, I am unsure about how to modify it. Specifically, I am attempting to ...

Error message: Action Cable could not execute the command due to a RuntimeError. It is unable to locate the subscription with the given

There seems to be an issue arising when I attempt to make a call to perform upstream on an Action Cable channel named 'UsersChannel'. The error message that is being displayed in its entirety is as follows: An error has occurred while attempting ...

Replacing CSS using jQuery/JavaScript

Recently, I encountered a challenge with a table that had its border set as 1px solid silver from an external style sheet (a .css file over which I had no control). The CSS code responsible for styling the table was as follows: my_table tbody td { font: ...

Instructions for rotating a sphere simultaneously along the x, y, and z axes

Seeking assistance on how to properly rotate an image along all three axes using the Three Js library. Currently, rotation along one axis works fine, but when attempting rotation along all three axes, the results are abnormal. I have read about using quate ...

In JavaScript, the code fails to verify the email entered through a form

Hi, I'm not sure if this is the right place to ask my question but I'm having trouble with a code that I can't seem to figure out. I've tried various algorithms but none of them seem to work. My issue involves validating an email from a ...

Expanding Text Box

My goal is to create a textarea that automatically adjusts its size as the user types or pastes long text into it. This is my current implementation. class AutoResizeTextArea extends InputBase { render() { const { label, placeholder, wrap, ro ...

If the href attribute is set to "#" or the target attribute is set to "_blank", then the <a> request cannot be prevented

I have a registration site that triggers a warning window whenever a user clicks on any link during the registration process. However, I want to exclude <a> tags with href="#" and target="_blank" attributes from this behavior. Essentially, I want to ...

Learn the steps to emphasize the first row of a material table using React

Within my react application, there is a material table that I have styled using the following code snippet: <MaterialTable options={{ exportButton: true, exportAllData: true, pageSize: 5, pageSizeOptions: [5, 10, 15 ...