What is the mechanism behind the setTimeout function as an asynchronous timer when we specify a specific duration?

Can you identify the coding instructor, possibly Net Ninja or Fireship, who explained that in asynchronous setTimeout, it promises to run after a minimum time of 1 second but may actually take longer (e.g. 1015 milliseconds or 1200 milliseconds)? What happens if we include something in the method that clearly requires more than 1 second?

setTimeout(() => {
console.log("Delayed for 1 second.");
}, "1000")

Answer №1

It seems like there may be a misunderstanding here.

Just to clarify, the function you provide to setTimeout will only execute after the specified time has passed.

The duration you set has no impact on how quickly the function runs once it is triggered.

If the main event loop is occupied with running other tasks, it can cause a delay in executing the function.

setTimeout(() => {
  console.log("This message will appear after 1 second.");
}, 1000);

const now = new Date();
const ten_seconds_in_ms = 10 * 1000;
const ten_seconds_later = new Date(now.getTime() + ten_seconds_in_ms);

console.log("Initiating a while loop that lasts for 10 seconds");

while (new Date() < ten_seconds_later) {
  // Blocking execution for 10 seconds
}

console.log("The while loop has ended, and the main event loop is now free to handle the task queue");
Please note that the logs in this code snippet should display correctly in your browser's developer tools. However, they may cause delays in rendering on the SO viewport due to the blocking nature of the while loop.

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

Having trouble with Laravel 5.5 and ajax file uploads?

I am encountering an issue with Laravel 5.5 while trying to get an ajax file. I can successfully receive the file using $_FILES, but $request->file() is not working as expected. Here is the code in question. Below are the HTML & Ajax elements: <html&g ...

How can you create a jQuery fade in effect for a single <li> element

I'm in the process of developing a task management app that generates a new li element every time a user adds an item. However, I am facing an issue where fadeIn() is activating for every li on the page whenever a new item is added. Does anyone have s ...

Having trouble configuring Angular-UI Router to work properly with Apache server

My web app is running on my PC through an Apache server, but I'm having issues with the routing provided by ui.route. It seems that the simple state I defined is never being reached. To troubleshoot, I added a wildcard to catch all paths and found th ...

Node.js routing currently lacks the ability to easily verify the presence of a JWT token for every route

I have a node application where, upon routing to ('/login') with valid credentials, I generate a JWT token with an expiry time and direct the user to the next page. If the user tries to access any other route directly (e.g., '/home') af ...

Remove background image when input form field is in focus

I am currently experimenting with the following approach: $('input').on('click focusin', function() { $('.required').hide(); }); However, it appears that this logic is not functioning as intended. Here is an ...

The conditional statement for multiplying in JavaScript

I have a JavaScript function that selects a report number based on multiple parameters (2 checkboxes, 3 dropdown fields), and the current implementation involves a complex conditional statement as shown below: switch(ReportNumDrop) { case 0 ...

Breaking apart web addresses and their attached parameters

I am attempting to extract the part of a URL that comes after the last forward slash (/) and before the querystring. While I have been successful in obtaining the last segment of the URL, I have encountered difficulty in removing the querystring from it. ...

Steps for embedding a webpage within a div element

I am facing an issue while trying to load a web page within a div using an ajax call. Unfortunately, it's not working as expected and displaying the following error message: jquery.min.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread ...

Express encountered a simple web application error

Greetings, this marks my debut post. As a coding novice, I have been following tutorials on opentutorials.org/course/2136/11950 I attempted to troubleshoot errors in my code, but unfortunately I've hit a roadblock. Upon accessing the site, it displa ...

Navigating with Reach Router only updates the URL, not the component being rendered

Is there a way to programmatically navigate using Reach Router in React? I have noticed that when updating the URL, the route does not render. Even though the URL changes, the original component remains displayed according to the React developer tools. Ho ...

What approach provides the most effective way to navigate through an NPM Package?

I have an idea to enhance a particular open source NPM package. Although I understand the necessary steps, it would be incredibly beneficial to have the ability to debug the package while it is in operation. Is this achievable? ...

Replace the typical bootstrap text class with stylish and modern google material icons

As a newcomer to the world of javascript, I acknowledge that my approach may not be ideal... I'm attempting to modify the color of a material icon upon clicking it. Essentially, I want to toggle it on and off. The challenge lies in the code's in ...

What is the best way to have a text field automatically insert a hyphen after specific numbers?

Is there a way to make a text field insert hyphens automatically after certain numbers? For example, when typing a date like 20120212, could we have the input automatically formatted with hyphens after the first 4 digits and the second two, so it displays ...

Having trouble with loading images from the assets folder, keep encountering a 304 error

While attempting to load a PNG file from the assets folder, I encountered a 304 error. My goal is to load images from the assets folder. const path = require('path'); const express = require('express'); const webpack = require('we ...

Fetch response headers not being detected by Web Worker

Currently in my chrome extension, I'm utilizing web workers to collect response header cookies from a specific website. Interestingly, when I execute the request on the main thread, the response contains all the expected cookies. However, when the exa ...

VueJS 3 custom Checkbox fails to update UI upon clicking

I'm attempting to implement a customized checkbox using Vue 3 and the composition API based on this example. However, despite confirming through devtools that all my props and bound data are successfully passed from the parent component to the child c ...

Is there a way to automatically change specific characters as a user types in an input field?

I'm facing an issue with replacing some characters dynamically. The goal is to ensure that user-input text is URL-friendly for constructing a URL: function slugify(string) { const a = "àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïí ...

Nested routes are arranged in the depths and a variety of components appear depending on the path of the

I've encountered a situation where I have deeply nested routes in my routes.js file. The code snippet below shows that depending on the route, I need to render different components. For instance, if the route is for products, I should render the Produ ...

Let's unravel this JavaScript enigma: the code snippet window.confirm = divConfirm(strMessage) awaits

Imagine a scenario where you have an old website with a lot of existing JS code. If a user wants to update all the alert messages to modern, stylish Div-based alerts commonly used in jQuery, YUI, Prototype, etc., there are primarily three types of JS dialo ...

Achieving nested routes without the need for nested templates

My Ember routes are structured like this: App.Router.map(function() { this.resource("subreddit", { path: "/r/:subreddit_id" }, function() { this.resource('link', { path: '/:link_id'} ); }); }); However, ...