What is it about the setTimeout function that allows it to not block other

Why is setTimeout considered non-blocking even though it is synchronous? And on which thread does it run if not the main thread?

Answer №1

Why doesn't the setTimeout function return a promise?

The reason is that it was created before Promises were introduced to JavaScript.

Is setTimeout considered synchronous or asynchronous?

It operates synchronously but schedules a function to be executed at a later time.

Why does setTimeout return a number instead of a promise?

The returned number is intended for use with clearTimeout.

Can await be used with setTimeout?

await can only be used with promises.


You have the option to wrap setTimeout in a promise and resolve it within the callback passed to setTimeout. Here's an example:

await new Promise( resolve => setTimeout(() => {
    // Perform actions after 1 second
    // then:
    resolve();
}, 1000);

Answer №2

The setTimeout function operates synchronously. Its callback is registered by the event loop during the timer phase and will be executed in an asynchronous manner.

Answer №3

Timeout functions are inherently asynchronous, allowing them to be non-blocking and executed on the main thread.

In JavaScript, the callbacks of timers like setTimeout and setInterval are stored in heap memory until they expire. When a timer expires, the event loop retrieves the associated callback and executes it in order of their delay, continuing this process until the timer queue is empty.

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

Exploring the functionalities of AngularJS' ng-options when working with select elements

In my search through other posts, I came across this issue but couldn't find a solution. Here is the array in question: $scope.items = [ {ID: '000001', Title: 'Chicago'}, {ID: '000002', Title: 'New York' ...

Setting up a connection to MongoDB on a local network using express and mongoose

As I set up a server with express and mongoose, my goal is to make it accessible on other devices within my local network. To achieve this, I configured the bind_ip variable to 0.0.0.0 in the Mongodb configuration file. const connection = mongoose .co ...

Utilizing a Clear Button to Reset Specific Fields in a Form Without Clearing the Entire Form

I am currently working on a multipart form that includes 'Name', 'Email', and 'Phone Number' fields. It's important to note that the phone number field is actually composed of 10 individual single-digit fields. To enhan ...

Connect parent-child models with checkboxes

Currently, I am working on an application where I need to link checkboxes for a role-based menu. The challenge lies in dealing with parent-child checkboxes and ensuring that the values of checkboxes are checked based on user input 1, 1.1, 1.2, 2, 3. Despi ...

How to switch between classes for elements and return to the original one when none of the elements is chosen

Hello there, I need some assistance. Here's the scenario: I am working with a grid of six items. My goal is to have the first item in the grid become active by default. When the user hovers over any of the remaining five items, I want the active clas ...

Transitioning from a traditional CURL method to utilizing AJAX and XMLHttp

I'm currently facing a challenge converting the curl code from an API named TextRazor to AJAX XMLHttp due to limitations on the platform I am working with. Despite trying various solutions shared by the community, I have been unsuccessful in retrievin ...

What is the best way for Flask to host the React public files?

When working with React, I created a folder called ./public/assets, and placed an image inside it. Running npm start worked perfectly fine for me. However, after running npm run build in React, I ended up with a ./build folder. To solve this issue, I moved ...

chart.js version 3 does not display the correct date data on the time axis

Struggling to make chart.js work with a time axis is proving to be quite challenging for me. The code I have is as follows: <html> <head> <script src="https://cdn.jsdelivr.net/npm/moment"></script> <script src="https://cdnjs.clo ...

The steps to activate the "Begin Now" button

Currently grappling with an issue regarding the implementation of a Get Started button for my messenger bot. I am utilizing node.js and the Express framework. Despite my efforts, it seems that my current approach is not yielding the desired result: functi ...

What is the strategy to load a div exclusively when triggered by a click event, instead of loading it

Can anyone assist me with a problem I am facing on my scripting page? I am currently working on a website that showcases properties. I would like to know how to prevent a specific div from loading when the page initially loads, and instead have its content ...

Buffer Overflow - Security Audit - Node JS TypeScript Microservice Vulnerability Scan Report

Person Data Schema: import JoiBase from '@hapi/joi'; import JoiDate from '@hapi/joi-date'; const Joi = JoiBase.extend(JoiDate); const personDataSchema = Joi.object().keys({ person: Joi.object().keys({ personId: Joi.string().max( ...

Removing connected entries with pre middleware on mongoose

I currently have 3 different schemas: Building const BuildingSchema = mongoose.Schema({ address: { type: String, required: true }, numberOfFloors: { type: Number, default: 0 }, }); Apartment const RoomSchema = mongoose.Schema({ roomNumber: { type: ...

onmouseleave event stops triggering after blur event

I am facing an issue with a mouseleave event. Initially, when the page loads, the mouseleave event functions correctly. However, after clicking on the searchBar (click event), and then clicking outside of it (blur event), the mouseleave functionality stops ...

What causes the Vue.http configuration for vue-resource to be disregarded?

I am currently utilizing Vue.js 2.3.3, Vue Resource 1.3.3, and Vue Router 2.5.3 in my project while trying to configure Vue-Auth. Unfortunately, I keep encountering a console error message that reads auth.js?b7de:487 Error (@websanova/vue-auth): vue-resour ...

Steps to create a scrollable material-ui Modal

After setting up a Modal, I encountered an issue where the text describing my app inside the modal was overflowing, making it impossible to see the top and bottom parts. To solve this problem, I want to implement scroll functionality within the component s ...

I encountered a problem while trying to incorporate the solution that prompts another button click event

Interesting topic: JQuery / JavaScript - triggering button click event from another button <input type="submit" name="savebutton" id="uniqueOne" /> <input type="submit" name="savebutton" id="uniqueTwo" /> I have implemented a feature on my si ...

Creating a process to produce a random number and send it directly to an automated email

I'm currently utilizing a form builder from jqueryform.com to construct a registration form. My goal is to have each registered user assigned with a unique account number, which will be a randomly generated 6-digit number. Additionally, I want the pro ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

The $postLink() method in the controller is encountering a null value for this.$scope

class pageController { constructor($scope, MyEditableGrid) { this.$scope = $scope; this.MyEditableGrid = MyEditableGrid; this.myEditableGrid = { appScope: this.$scope, ..... } } $postLink ...

The resize function fails to trigger when it is required

Struggling to get this code working properly. If the window width is greater than 800, I want 6 images with a red background. If the window width is less than 800, I want 4 images with a blue background. I need this functionality to work both on r ...