The setInterval function with a time interval set to 1ms does not appear to function exactly as a 1ms delay

I'm attempting to measure the duration of a file download using an HTTPRequest as seen below:

function getFile() {
    'use strict';
    var url = "data.bin";
    var rawFile = new XMLHttpRequest();
    var timer_var = setInterval( theTimer, 1 );

    rawFile.open("GET", url, true);
    rawFile.onreadystatechange = function () {
        if(rawFile.readyState === XMLHttpRequest.DONE && rawFile.status === 200) {
            toLog(rawFile.responseText);
            window.clearInterval(timer_var);
            toLog("Milliseconds for download: " + time_taken);
        }
    };
    rawFile.send(null);
}

function theTimer() {
    'use strict';
    toLog(time_taken);
    time_taken++;
}

It is evident that I have utilized setInterval to invoke theTimer every millisecond. The function theTimer() simply increments a variable, which theoretically should hold the time in milliseconds of how long the interval was executing.

Upon completion of the download, I present the data, stop the timer, and exhibit the time in milliseconds. Nonetheless, the recorded value does not align. It should be close to 2 seconds, yet it remains at around 250ms.

Why is the setInterval not truly every 1ms?

Answer ā„–1

According to the relevant documentation:

Time Delay

The specified time in milliseconds (thousandths of a second) that the timer should wait between executions of the given function or code. If the specified delay is less than 10, the value 10 is used instead. It is important to note that the actual delay could be longer;

(As per Mozilla, similar patterns can be observed in other browsers)

There is also a mention of the documentation regarding setTimeout which explains why "the actual delay may be longer".

To sum it up:

  • There is a minimum delay set in the specifications for nested timeouts
  • Timeouts may be constrained by inactive tabs to decrease the load
  • The webpage/browser/operating system may be occupied with other processes

In current browsers, a technique utilizing window.postMessage appears to be available.

Answer ā„–3

By multiplying the outcome by 4, you will achieve the actual number in milliseconds. I experimented with this specifically in the Chrome 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

My server keeps crashing due to an Express.js API call

I'm completely new to express.js and API calls, and I'm stuck trying to figure out why my server keeps crashing. It works fine the first time, rendering the page successfully, but then crashes with the error: TypeError: Cannot read property &apo ...

In JavaScript, not all elements are removed in a single iteration, even if the condition is consistently met

I'm currently attempting to compare two arrays containing multiple objects and remove elements based on a condition. To my surprise, while testing in Chrome's console, I noticed that the first array (arr1) is not being emptied even though I am us ...

What causes immediately invoked functions within event handlers to be executed before the event is triggered?

let b = (function maria() { alert("ee"); })(); * this code runs as soon as the page loads * <button onclick="b">Click me</button> * this code only runs when button is clicked * <button onclick="alert('ee')">Click m ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

Is NextJS rendering solely on the server, or is it capable of rendering on both

Within my users.js JSX file, I have an exported component that looks like this: ... return <MainContainer keywords="users"> export default Users During the process of SSR/SSG, the browser displays the users HTML (comprising of <li> t ...

Adding a new value to an array of objects without altering the existing values in ReactJS and NextJS

I have a JSON file containing image names that I need to organize into a Key-Value Object. I am currently using regex to create keys by removing "-img[image No]". However, I am having trouble storing all the image names in the array without overwriting pre ...

Retrieve a specific column value upon button click in HTML and JavaScript

I am faced with a table containing multiple columns, each row equipped with an edit button. https://i.sstatic.net/3S5VP.png Upon clicking the edit button, a modal view pops up where users can input values that are then sent via AJAX to my controller. ht ...

Ways to stop a ng-click event on a child div controller from activating an ng-click in the parent controller?

http://plnkr.co/edit/gB7MtVOOHH0FBJYa6P8t?p=preview The example above demonstrates a parent-child controller setup. In the child controller, when a button is clicked, it displays the div showPop and emits an event to the $rootScope. Upon receiving this e ...

Determining where to implement the API display logic - on the server side or

Currently, I am in the process of restructuring an API that deals with user profiles stored in one table and profile images in another. The current setup involves querying the profiles table first and then looping through the images table to gather the ass ...

Singleton constructor running repeatedly in NextJS 13 middleware

I'm encountering an issue with a simple singleton called Paths: export default class Paths { private static _instance: Paths; private constructor() { console.log('paths constructor'); } public static get Instance() { consol ...

Utilizing the Ternary Operator within ReactJs Card Headers

Is it possible to include a ternary operator in the title of CardHeader using ReactJS? I am able to include the first name but encountering issues with including the last name as well. <CardHeader title={(firstName ? firstName : "") + " " + (lastName ...

Tips for containing a moving element within the boundaries of its container div

I have a dynamic box placed inside another box, and I want to restrict its movement within the boundaries of the parent container. How can I achieve this? In simpler terms: I need the frog to stay within the frogger. HTML <div id="frogger"> ...

Identifying all Images with JavaScript, Including Asynchronous Ones

Is it possible to use JavaScript to identify all images within a document, even those that are loaded asynchronously (possibly after the DOM is fully loaded)? I am interested in developing a function that can determine if Google Analytics has been loaded ...

Is it possible to horizontally center an auto-fill grid using only CSS?

I would like to fill my page horizontally with as many blocks as possible and center the result. My goal is to have a grid that can resize when the window size changes: wide window xxx small window xx x Is it possible to achieve this without using Java ...

Struggling to Add angular-websocket to a MeanJS v0.4.1 Application: Dealing with an 'Unknown Provider' Error

I'm encountering some challenges while using angular-websocket in a controller within my MeanJS project. The version of MeanJS Iā€™m working with is v0.4.1. To begin, I installed it by running: bower install angular-websocket --save This creat ...

Show the selected checkbox options upon clicking the submit button

Having trouble setting up a filter? I need to create a feature where checked values from checkboxes are displayed in a specific div after submitting. The display should include a 'Clear All' button and individual 'X' buttons to remove e ...

What is the process for arranging multiple text boxes beside a radio button upon selection?

Displayed below is the HTML code for a page featuring three radio buttons- <html> <body> <form> <input type="radio" name="tt1" value="Insert" /> Insert<br /> <input type="radio" name="tt2" value="Update" /> Update<b ...

Selecting objects using a mouse pointer in Three.js

Is it possible to implement mouse picking on imported 3D models like a .obj file in Three.js? I've found plenty of tutorials for default objects, but I'm struggling to display a sphere at the exact position where the user clicks the model. Can an ...

RAZOR - Strip image elements from variable with HTML content

In the code snippet below, I am using a helper to display content: @Html.Raw(Model.PageData.PageContent) My goal is to filter out any image tags that may be present. I have explored methods like .substring(), but they require specific indices or string n ...

Create a PHP file with various functions and access them using jquery.post or jquery.get in a separate JavaScript file

Is there a way to call multiple PHP functions from my JavaScript file using Jquery.post? Typically, we use Jquery.post to call a PHP file and pass various values as post data. function new_user(auth_type, tr_id, user_name, email) { $.post("bookmark.p ...