Do GPU-intensive animations get impacted by the CPU's load?

I have set up a special compositing layer for a div with the following unique styles:

div {
  position: absolute;
  height: 50px;
  width: 50px;
  background: #900;
  top: 100px;
  left: 200px;
  will-change: transform;
  transform: translateZ(0);
}

After that, I added an animation to it using the Web Animation API:

document.getElementById("box").animate(
  [
    { transform: 'rotate(0) translate3D(-50%, -50%, 0)' },
    { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)' }
  ], {
    duration: 500,
    iterations: Infinity
  }
);

As far as I can tell, this animation is now being managed by the GPU and this layer acts independently from the rest of the page layout, allowing the GPU to apply changes without computational interference.

What I am struggling to comprehend is when I run a CPU-intensive function, the animation completely halts until the function finishes executing:

function mySlowFunction(baseNumber) {
    console.time('mySlowFunction');
    var result = 0; 
    for (var i = Math.pow(baseNumber, 10); i >= 0; i--) {       
        result += Math.atan(i) * Math.tan(i);
    };
    console.timeEnd('mySlowFunction');
    return result;
}

setTimeout(() => mySlowFunction(5), 3000);

Is there a way to prevent this interruption?

https://jsfiddle.net/Lsmw85rv/4/

Answer №1

It is possible for them to still be affected by CPU load.
The update the rendering algorithm is integrated within the Event Loop, so if there is any blockage in the event loop, it would also impact the rendering process.

In order to tackle this issue, implementors are advised to "spin the event loop" when dealing with lengthy code execution, ensuring that the user interface remains responsive (allowing non-JavaScript animations to function smoothly). However, the implementation of this advice may differ across various platforms.

For example, I did not observe any slowdown on my Firefox browser due to your script, whereas on Chrome, the rendering delay was evident.

To address this concern effectively, as mentioned in previous comments, running the blocking script in a separate thread using a Web Worker would offer a robust solution.

document.getElementById("box").animate(
  [{
      transform: 'rotate(0) translate3D(-50%, -50%, 0)'
    },
    {
      transform: 'rotate(360deg) translate3D(-50%, -50%, 0)'
    }
  ], {
    duration: 500,
    iterations: Infinity
  }
);

function mySlowFunction(baseNumber) {
  console.time('mySlowFunction');
  const now = performance.now();
  while (performance.now() - now < baseNumber * 1000);
  console.timeEnd('mySlowFunction');
}

setTimeout(() => mySlowFunction(3), 3000);
#box {
  position: absolute;
  height: 50px;
  width: 50px;
  background: #900;
  top: 100px;
  left: 200px;
  will-change: transform;
  transform: translateZ(0);
}
<div id="box"></div>

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

I am having trouble deactivating an HTML button using my JavaScript function

I have been working on a feature where a button in HTML is supposed to be disabled until a specific textbox is filled out. Once the textbox has content, the button should become enabled and save the user's name along with their score from a previous g ...

Aggregate the values of a key in an associative array and organize them by their respective key

I have a table set up like this: <table> <thead> <th>PRODUCT</th> <th>QUANTITY</th> <th>AREA</th> <th>PRICE</th> <th>TOTAL</th> <tr> &l ...

Error: AngularJS is experiencing an injector module error that has not been caught

I have set up an Angular boilerplate that includes various elements such as meta tags, CDN links, and script tags. However, I am encountering a persistent error in my console and cannot figure out the root cause of it. https://i.stack.imgur.com/qPGby.png ...

I encountered difficulty in assigning a JSON response to a variable, both with and without using JSON.parse()

I'm in the process of creating a website that, among other things (and crucially for this particular issue), stores your current location data in a variable by fetching it from the ipinfo API (https://ipinfo.io/json) After encountering the problem of ...

Show the response obtained after making a POST request

In my current project, I am utilizing vanilla JavaScript to send a POST request to my Flask App. I have implemented a validation feature that checks for duplicate usernames when a user is signing up. If the username already exists, a 406 status response is ...

Instructions for creating a scrollable unordered list when it reaches its maximum capacity

My HTML code has a <ul> element with the following structure: <ul id="messages"> </ul> In my HTML file, I have not specified any <li> items. However, in my JavaScript code using jQuery, I dynamically add <li> items to the & ...

Is there a way to use JQuery to dynamically generate a new select box with specific options?

I am looking to dynamically create a new select box based on the value selected in an existing select box using jQuery. Currently, the code we have implemented is not functioning correctly. <script src="http://code.jquery.com/jquery-1.5.min.js">&l ...

The radio button fails to trigger the setState function in React

In my React program, I have implemented a method to update the state and modify a specific value for a Radio button: The state : class App extends Component { constructor(props) { super(props); this.state = { checked: [], expanded: [], ...

What is the best way to parse this JSON data?

Here is a string that I have: [{"data1":"A"},{"data2":"B"},{"data3":"C"}] Using jQuery, I converted this string to JSON: test_json = $.parseJSON('[{"data1":"A"},{"data2":"B"},{"data3":"C"}]'); After conversion, I obtained 3 objects: I am uns ...

Utilize a standard JavaScript function from a separate document within a function of a React component

I am facing an issue where I need to incorporate a standard JavaScript function within a React component function. The script tags are arranged in the footer in the following order: <script src="NORMAL JAVASCRIPT STUFF"></script> // function ...

Issues encountered when trying to use the export default syntax in Vue components

Programming Issue I attempted to execute the provided code, but unfortunately, it does not work and no output is visible in the browser. Is there an alternative method for writing code within <scripts setup> </script>? I have understood that f ...

What is the best way to format the information when using response.send() in express.js?

I need help with customizing the content I'm returning in the app.post() method. Is there a way to do this? Below is an example of the app.post() code: app.post("/",function(req,res){ const query = req.body.cityName; const cityName = query.charA ...

Structuring files with AJAX, PHP, Javascript, and HTML

Explaining my dilemma in detail might be a bit abstract, but I'll try to do my best. In one of my PHP files, I have HTML code that includes text boxes and a submit button. This file serves as the main page and is named mainHTML.php The text boxes ar ...

Looking to transition from Angular 1.5x to ReactJS, what is the most effective method for conducting A/B tests and exploring different views?

As I transition part of the UI code to ReactJS, I am considering A/B testing my app for instrumentation. I have looked into Intuit's Wasabi as a potential framework but found its setup process in production to be cumbersome. I am seeking an alternativ ...

Create a stylish border around an ion-card using a sleek black bar

I have a card element with a title and subtitle, and I want to add a black bar above the header. <ion-list> <ion-card (click)="onEventClick(event.id)" *ngFor="let event of events"> <ion-card-header> ...

The AngularJS templates' use of the ternary operator

Is there a way to implement a ternary operation in AngularJS templates? I am looking for a way to apply conditionals directly in HTML attributes such as classes and styles, without having to create a separate function in the controller. Any suggestions wo ...

What is the best way to create separate arrays for every element in my object, containing a total of four arrays to efficiently produce a weekly forecast?

Hey there, I'm back with an update on my ongoing project. I've encountered a major challenge while trying to incorporate a 7-day forecast display in my app. Something along these lines: https://i.stack.imgur.com/xJA4M.png https://i.stack.imgur. ...

From transitioning from AngularJS to the latest version Angular 8

I have an Angular application where I need to update some old AngularJS code to work with Angular table.html <table ngFor="let group of vm.groups" style="float: left"> <thead> <tr> <th><b>Sl. No</b ...

Troubleshooting: Node.js Express Server GET Handler Failing to Function

Recently, I've been attempting to build a GET request handler in Express.js. Here's the snippet of code I've put together: // include necessary files and packages const express = require('./data.json'); var app = express(); var m ...

Changing a complex object within a nested array of a BehaviorSubject

I'm currently working on an Angular app. Within my service, DocumentService, I have a BehaviorSubject that holds an array of Documents. documents: BehaviorSubject<Document[]> Let me provide you with some insight into the various classes I' ...