Is JavaScript's setTimeout 0 feature delaying the rendering of the page?

Based on information from this StackOverflow post

The process of changing the DOM occurs synchronously, while rendering the DOM actually takes place after the JavaScript stack has cleared.

Furthermore, according to this document from Google, a screen refresh rate of 60fps is equivalent to refreshing every 16ms. In light of this, the following example code was created:

<!DOCTYPE html>
<html>
    <head>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                document.querySelector('#do').onclick = function() {
                    document.querySelector('#status').innerHTML = 'calculating...';
                    // setTimeout(long, 0); // will block
                    setTimeout(long, 1); // will not block
                };

                function long(){
                  let result = 0
                  for (let i = 0; i < 1000; i++) {
                    for (let j = 0; j < 1000; j++) {
                      for (let k = 0; k < 1000; k++) {
                        result += i + j + k;
                      }
                    } 
                  }
                  document.querySelector('#status').innerHTML = 'calculation done';
                  document.querySelector('#result').innerHTML = result.toString();
                }
            });
        </script>
    </head>

    <body>
        <button id='do'> Do long calc!</button>
        <div id='status'></div>
        <div id='result'></div>
    </body>
</html>

You can access the corresponding jsfiddle example via this link.

After experimenting with the code, it was observed that blocking occurs when the time delay is under 12ms, and happens more frequently with shorter delays.

There are two possible interpretations to consider:

  1. In this scenario, only setTimeout with a time delay exceeding 16ms should not cause blocking, as both 0ms and 1ms delays are significantly less than 16ms;

  2. Immediately after calling setTimeout and adding long to the message queue (with an optional delay), the call stack is empty, therefore in both cases setTimeout should not cause blocking and 'calculating...' should always be displayed.

If you spot any flaws in this understanding, please provide feedback.

Answer №1

Your browser might be causing the delay due to throttling, according to this source.

It seems that most browsers ignore a timeout value of 0, so it could be helpful to check the DOM_MIN_TIMEOUT_VALUE specific to your browser.

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

To achieve two-way binding with a scope variable, it is necessary to enclose it within an

I am in need of creating a basic search feature for some items. I have designed a simple control with a button that clears the search query: <div class="item item-input item-button-right"> <i class="icon ion-ios-search placeholder-icon">&l ...

Storing data locally in PhoneGap using localStorage via AJAX calls is a common requirement for

Our mobile application is built with cordova [phonegap] and we are looking to implement offline saving of results into the cache memory. The results are fetched from a PHP server and displayed in a webview using ajax and javascript. I have tried using loc ...

Is it no longer possible to use v-for to iterate over translations in Nuxt 3 and @nuxtjs/i18n?

Imagine having an Array stored in our translations file en.js section: { title: 'This value is a string and it works perfectly', highlighted: [ { title: 'Highlighted title 1', text: 'Highlighted text ...

The breakdown of an object literal in JavaScript

What is the reason that we cannot access the second item in the object literal the same way as the first? var foo = {a:"alpha",2:"beta"}; console.log(foo.a) -> printing 'alpha' correctly console.log(foo.2) -> Error: missing ) after argumen ...

Converting a UUID from a string to an integer in JavaScript

Need help passing a UUID to a function that calls an endpoint to delete a blog. The UUID is in string format like "9ba354d1-2d4c-4265-aee1-54877f22312e" and I'm encountering a TypeError: Cannot create property 'message' on string '9ba35 ...

Efficient Techniques for Deleting Rows in a Dynamic JavaScript Table

I'm facing an issue where I want to remove each line added by the user, one by one. However, my current program is removing all the rows from the table instead of just one at a time. The objective is to allow the user to remove a specific row if they ...

The issue of data not being transmitted when an ajax jquery form is modified

Each item in the cart/order has its own unique form with IDs created in a loop (e.g. 'id'=>'cart_'.$line )(cart_1,cart_2), along with an update link for each form within the loop. See the code snippet below: echo form_open($control ...

Could you lend a hand in figuring out the root cause of why this Express server is constantly serving up error

I am encountering a 404 error while running this test. I can't seem to identify the issue on my own and could really use another set of eyes to help me out. The test involves mocking a request to the Microsoft Graph API in order to remove a member fro ...

Sending an Array from JavaScript to Asp.net Core

Below is the javascript code that invokes the asp.net CustomHeatMapDate function $('.Date').change(function () { var data = []; console.log(); var dateList = [{"Date":"03/23/2016"}, {"Date":"03/24/2016"}]; $.ajax({ async: ...

utilizing eval() in order to retrieve a pointer to an include

I am currently developing a form widget where the form schema is fetched from an API and generated dynamically. The library I am using for this purpose (vue-form-generator) comes with built-in validators that are directly referenced within the library itse ...

The Slice method is malfunctioning after the array has been filtered

I am currently working on creating a news portal app using Next JS, Redux, mongoose, and Express. My Issue is: While I am able to filter specific items from an array successfully, I encounter problems when attempting to display a specific number of items, ...

Steps for transforming an array of arrays into a JSX element within a React component, where each nested array contains its own clipPath

The array_groups variable consists of an array containing multiple arrays. Each inner array holds the coordinates of regular circles that are closely spaced together. The intention is to clipPath these inner circle arrays as a whole. When the mouse hovers ...

Unable to set cookies properly

I am currently running a svc service on crm.mch.be. When a specific request is made, it returns a response with the following headers: Access-Control-Allow-Credentials: true Access-Control-Allow-Headers: X-Requested-With,Content-Type Access-Control-Allow- ...

I'm stumped trying to understand why I keep getting this syntax error. Any thoughts on how to fix it?

Our team is currently working on creating a dynamic SELECT box with autocomplete functionality, inspired by the Standard Select found at this link: We encountered an issue where the SELECT box was not populating as expected. After further investigation, ...

Tips for saving the web address and breaking down each word

Hello, I am familiar with how to store URL parameters using the following JavaScript code. However, I am wondering if there is a way to store each word that comes after a slash in a URL. For example, let's consider the URL: http://localhost:9000/Data ...

Transitioning to Material-ui Version 4

During the process of upgrading material-ui in my React Application from version 3.9.3 to version 4.3.2, I encountered an error message stating TypeError: styles_1.createGenerateClassName is not a function. I am feeling lost when it comes to transitioning ...

Enhancing HTML "range" element with mouse scroll functionality for incrementing values in step increments

I'm working on developing a scroll feature that operates independently from the main window's scrolling function. I aim to trigger specific events in the primary window based on interactions with this separate scrollbar. The only solution I coul ...

I am experiencing difficulty with Three.js rendering textures from my planet constructor function

I am facing an issue with my function that is supposed to create a 3D object (a planet) using orbital parameters and texture images from a dataset. Strangely, the textures are not rendering when I use StandardMaterial or PhongMaterial, even though they wor ...

Turn only one bracket on the accordion

When clicking on a specific header, I want only one chevron to rotate instead of all the chevrons rotating. I am currently unsure how to specify which chevron should rotate individually. My project is in ASP.NET MVC 5 and I am using razor view to loop th ...

What is the best way to transfer data between files in Python?

My website code is (ser.html) <div> <a v-bind:href="'ser/'+post.name"> {{post.name}}</a> </div> I am trying to transfer post.name data from this file to another one (det.html). In my views.py file: from django.shortcut ...