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

"Obtaining a MEAN response after performing an HTTP GET

I'm currently in the process of setting up a MEAN app, however I've hit a roadblock when it comes to extracting data from a webservice into my application. While returning a basic variable poses no issue, I am unsure how to retrieve the result fr ...

Struggling to deal with conditionals in Express

Just starting with Express and I've come across the following code: const { response } = require("express"); const express = require("express"); const app = express(); app.get("/api/products/:id", function (req, res) { ...

AJAX issue: "Content-Type header is missing the multipart boundary parameter"

Currently, I am encountering an issue while attempting to transfer a file from localhost to a server. The error message displayed in my network console is as follows, with status code 500: "no multipart boundary param in Content-Type" To address this p ...

Error: Identical div IDs detected

<div id="tagTree1" class="span-6 border" style='width:280px;height:400px;overflow:auto;float:left;margin:10px; '> <a class="tabheader" style="font-size:large">Data Type</a><br /> <div class="pane">Refine sea ...

Instructions on incorporating domains into next.config.js for the "next/image" function with the help of a plugin

Here is the configuration I am currently using. // next.config.js const withImages = require("next-images"); module.exports = withImages({ webpack(config, options) { return config; }, }); I need to include this code in order to allow images from ...

Bot in discord.js refuses to exit voice channel

I've been struggling to get my bot to leave the voice channel despite trying multiple methods. Here's what I've attempted in the source code: Discord.VoiceConnection.disconnect(); Although this is the current code, I have also tested: messa ...

Showcasing pictures on ReactJS

I am currently working on developing an application to showcase images on my React webpage. These images have already been uploaded to a local folder. In order to integrate my React application with a NodeJS server and MongoDB, I connected the two. My goa ...

"Error: The functionality of finding places on Google Maps is not

I've encountered an issue while trying to integrate Google Maps into my Node application. The map is loading correctly and I'm able to retrieve my location. However, I am facing a problem with implementing the Google Places API code to allow user ...

What could be causing the select2 to not display the most up-to-date information in the control?

I have implemented a progressive search feature but it seems that the data returned is not populating the control properly. $("#selUser").select2({ ajax: { url: "/M01EngineeringData/GetFunctionalLocations", ty ...

Is there a way to identify when a radio button's value has changed without having to submit the form again?

Within this form, I have 2 radio buttons: <form action='' method='post' onsubmit='return checkForm(this, event)'> <input type = 'radio' name='allow' value='allow' checked>Allow ...

Using Ajax and jQuery to fetch information from a previous search query

I'm currently utilizing Ajax and jQuery for my chat feature. Some may find it overly complex, but as long as it works, that's all that matters. It's functioning properly on the first friend result, however, not on the others. The issue lies ...

Azure webhosting blocks the use of AJAX calls

There is a PHP script hosted on my Azure server that returns JSON when accessed through the browser. However, I am having trouble making an AJAX call to this script as none of my requests seem to go through. The issue remains unclear. You can see a failed ...

Ensuring that a group of items adhere to a specific guideline using JavaScript promises

I need to search through a series of titles that follow the format: <div class='items'> * Some | Text * </div> or <div class='items'> * Some more | Text * </div> There are multiple blocks on the page wit ...

The CORS middleware seems to be ineffective when used in the context of Node.js

I have set up my REST API on a Raspberry Pi server and connected it to the public using localtunnel. I am trying to access this API from a localhost Node.js application. The Node application is running on Express and includes some static JS files. However, ...

What is the best way to extract all <tr> elements from a <tbody> and then convert them into a String?

Below is an example of an HTML table: <table id="persons" border="1"> <thead id="theadID"> <tr> <th>Name</th> <th>sex</th> <th>Message</th> </ ...

The elements within the array are being refreshed accurately, however, a separate component is being removed

I have developed a component that has the ability to contain multiple Value components. Users can add as many values as they want, with the first value being mandatory and non-removable. When adding two new Value components, I provide input fields for name ...

Identifying Master Page Controls Post-Rendering

Within my asp.net projects, I have noticed a discrepancy in the control id on the master page's Contentplaceholder1. On my local server, the id appears as "ctl00_Contentplaceholder1_control" after rendering. However, when the application is deployed t ...

Browsing through an array of objects in PHP

Currently working on creating an array of objects using jQuery. var selected_tests = $("#selected_tests").find("tr"); jsonLab = []; $.each(selected_tests, function() { jsonLab.push({ test: ($(this).children()).eq(0).text(), amount: ($(this).chil ...

Determining when all $http requests have completed in AngularJS

After running multiple $http calls, I need to trigger an event only when all of them have been processed. Additionally, I must be informed if any call has failed along the way. Despite attempting solutions found on stackoverflow, such as using an intercept ...

Is it possible to determine HTML5 Context Menu Support using JavaScript?

While reviewing the Modernizr documentation, I couldn't find any information on creating a menu element and then checking its existence. However, I am concerned that even if the browser supports this, it may not support the type context. Do you have a ...