How come setting setTimeout to zero did not cause the code to enter an endless recursive loop?

I found this snippet of code on a website that discusses async callback functions and the event loop in JavaScript. I am curious as to why the line

timer = setTimeout(arguments.callee, 0)

does not create a recursive loop since it is being executed without any delay. According to logic, settimeout should be invoked repeatedly, preventing the following IF Statement from executing. However, in actuality, the if statement does get executed. Why?

var i = 0, diff = 0, d = new Date()

var timer = setTimeout(function() {
  diff += new Date() - d
  timer = setTimeout(arguments.callee, 0)
  if (i++==1000) {
    clearTimeout(timer)
    alert("Resolution: "+diff/i)
  }
  d = new Date()
}, 0)

Answer №1

As pointed out by @vld, Javascript in Browsers operates on a single thread due to the fact that browsers dedicate one thread for UI handling. This means that any asynchronous operation, such as setTimeout, will result in the code being queued for later execution. Once the current thread completes its tasks (like at the line d = new Date()), the engine will proceed to execute the previously queued code in sequence within the same thread. However, since the timeout has been cleared by this point, it will not trigger another execution.

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

Tips for downloading a file in React using raw file data

I've been struggling with a particular issue for the past couple of days and just can't seem to find a solution. It involves retrieving data from an API on our outdated system related to Attachments and other information. When I execute the query ...

The state in React's useState and useEffect seems to lag behind by one step

Understanding that updates to state are asynchronous and batched for performance reasons, I made the decision to utilize useState() and useEffect() in order to synchronize with my state before taking action. However, I encountered a problem where my state ...

Discover the process of retrieving an image from the backend with React and Node.js

Hey there! I'm currently working on a Housing blog using ReactJS and NodeJS. One of the tasks I tackled was creating a login controller in NodeJS to send user details, including the image path from the database, to the frontend. The image path is sto ...

Assign a variable name to the ng-model using JavaScript

Is there a way to dynamically set the ng-model name using JavaScript? HTML <div ng-repeat="model in models"> <input ng-model="?"> </div JS $scope.models= [ {name: "modelOne"}, {name: "modelTwo"}, {name: "modelThree"} ]; Any ...

Issues with react-bootstrap component Switches functionality not operating as expected

It looks like the bootstrap switches are not functioning properly. Even the documentation version is not working as expected <Form> <Form.Check type="switch" id="custom-switch" label="Check this switch" /> <Form.Check ...

"The 'BillInvoice' object must be assigned a primary key value before it is ready for this relationship" - Error Message

There is an issue in my Django project related to the creation of a BillInvoice and its associated BillLineItem instances. The error message I'm receiving states: "'BillInvoice' instance needs to have a primary key value before this re ...

Determine the y-coordinate of terrain in Three.js

I have acquired a Collada model of terrain and now wish to incorporate other models onto this terrain. To achieve this, I believe I need to retrieve the height coordinate (y) of the terrain based on specific x and z coordinates. Can someone please guide ...

Using JavaScript to create a search bar: Can "no results found" only show after the user has completed typing their search query?

How can I ensure that the "no match" message only appears after the user has finished typing in their search query, rather than seeing it while they are still typing "De" and the list displays "Demi"? usernameInput.addEventListener("keyup",function(){ ...

Select a configuration for binding an array of objects in AngularJS

Plunkr: http://plnkr.co/edit/RgNcSg?p=preview I have a dropdown menu displaying different "locations," which are sourced from an array of objects. Despite setting the object value in my controller, it does not appear selected in the dropdown menu. The HTM ...

Issue with Generating PDF File: Live Server Showing 403 Error

I am attempting to create a pdf file using the mPDF library in php. See below for my code: Initially, I am sending a large amount of data that needs to be written into the pdf file. JS: $.ajax({ url: '/backend_pdfgen/pdfgen.php', type: ...

Storing string data in JavaScript similar to how NSUserDefaults is used in iOS

Hey there! I'm diving into the world of Javascript and cordova applications and have a question. How can I save User(Login) details in a similar way to NSUserDefaults in iOS? ...

Can the serialization of AJAX URL parameters in jQuery be customized?

Is there a way to instruct jQuery or an AJAX call on how to format query string parameters other than writing a custom serializer? I am using a jQuery AJAX call and passing an object with URL parameters var params = {name: 'somename', favColors ...

Transforming javascript's array.map into php's array_map function

The following code snippet is written in JavaScript and consists of a hashmap array with keys and values. I have created a function using map that returns the values of the entered keys. var rule = { "c": "d", "a": "o", "t": "g", "h": "a", "e": "n", "n": ...

My PHP errors and success messages are not being displayed properly after an AJAX success

After making an AJAX call to submit a form, I would like to display either the PHP success message or error message upon completion. This is my current AJAX success function: success: function (data) { resultSuccess = $(data).find("#success") ...

How can we incorporate Django template tags into our jQuery/JavaScript code?

Is it possible to incorporate Django's template tags within JavaScript code? For example, utilizing {% form.as_p %} in jQuery to dynamically inject forms onto the webpage. ...

Emulate mobile view using Javascript and HTML simulation tool

I am trying to simulate the appearance of a website on a mobile phone. For example, consider the following code: <div> <div class = "col-md-6 col-sm-6 col-xs-12"> First </div> <div class = "col-md-6 col-sm-6 col-xs- ...

Visualizing JSON data on D3.js graph axis

Below is a snippet of JSON data that I successfully plotted on a d3js graph, using it as the x and y axis: var data = [ { "count": "202", "year": "1590" }, { "count": "215", "year": "1592" }, { "count": "179", "year": "1593" } ]; Now, I am facing a chal ...

I attempted to publish my React application using gh-pages and encountered the following error: "The argument for 'file' must be a string. However, it was received as undefined."

I encountered an issue while attempting to deploy my React application with gh-pages. The error message I'm facing states: "The 'file' argument must be of type string. Received type undefined." Initially, I suspected that the problem was wi ...

Can a function be returned using AJAX?

Suppose I am in need of initiating an ajax call to my server $.ajax({ type: 'POST', url: 'url/url', success: function(response){} }); and upon receiving a response from the server, I send some JavaScript code res.send(&qu ...

Attempting to seamlessly run a PHP file in the background by utilizing Ajax when a link is clicked

I am trying to execute a PHP file in the background when a link is clicked without the user being directed to the actual PHP file. After realizing that Ajax is the only way to achieve this, I attempted to implement it but encountered issues. Instead of ru ...