Understanding the sequence of operations in Javascript using setTimeout()

If I have the following code:

function testA {
   setTimeout('testB()', 1000);
   doLong();
}

function testB {
   doSomething();
}

function doLong() {
   //takes a few seconds to do something
}

When I run testA(), what happens after 1000 milliseconds, when the timeout for testB() is reached? Is JavaScript being single-threaded relevant here?

Here are some possibilities:

  • testB() will be queued up to execute after doLong() and any other functions it calls are finished.
  • doLong() will be immediately terminated and testB() will start executing.
  • doLong() will be given some extra time to finish before being stopped (either automatically or after user prompting) and then testB() will begin.
  • doLong() will be paused, while testB() starts. After testB() finishes, doLong() will resume.

What is the accurate answer to this scenario? Is it implementation-specific or part of the standard?

This related question may provide some insight, but it's not an exact match.

Feel free to share any links that could help in better understanding JavaScript execution flow.

Thank you!

*I am aware that not all browsers comply with standards :(

Answer №1

Your first guess hit the nail on the head:

The function testB() is scheduled to run after doLong() and any other functions it invoked have completed their tasks.

If testA takes longer than one second to complete, then testB will need to wait its turn.

Additionally, make sure to use setTimeout(testB, 1000) instead of setTimeout('testB()', 1000). Passing a string to setTimeout is frowned upon, similar to using eval, as it can be considered risky behavior according to experts in the field and may not win you any friends ;)

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

Exporting Javascript functions is not possible

Programming in TypeScript import { Component, OnInit } from '@angular/core'; import {loadCalendar} from '../../../../scripts/artist/artist-home'; import {activate_searchBar} from '../../../../scripts/search_bar_activate'; @C ...

The tooltip chart is not displaying all of its data

I create a dynamic tooltip with a custom chart inside of it. tooltip: { borderRadius: 15, borderWidth: 0, shadow: false, enabled: true, backgroundColor: 'none', useHTML: true, shared: true, formatter: function() { ...

Tips for sending an email to an address from a user input field in React.js/Express.js

I am currently developing an email application that allows users to send emails to any recipient of their choice. The challenge I'm facing is that I need a way to send emails to user-specified email addresses without requiring passwords or user.id det ...

What is the process for importing an md file in a create-react-app project using JavaScript?

Attempting to execute the blog example provided on Material UI's getting started page. However, encountering an issue with the source code: Inside blog.js import post1 from './blog-post.1.md'; . . . return( <Main>{post1}<Main/> ...

Is there a way to ensure that @angular/core is utilizing the most up-to-date version of zone.js in its peerDependencies configuration?

This code passes the test, but there is an issue: it('should successfully retrieve data when getDownloadProgress() is called', (done: DoneFn) => { let response = { 'process': {}, 'success': 'success ...

"Uncaught ReferenceError: $ is not defined - $function()" error in JavaScript/jQuery

When attempting to execute a JavaScript/jQuery function, an error is encountered when using Firebug: $ is not defined $(function()". The issue arises from the placement of the JavaScript code within a file named core.js that is referenced by index.php. W ...

"Exploring the world of Typescript's return statements and the

I'm currently grappling with a design dilemma in typescript. Within my controller, I perform a validation process that can either return a 422 response, which ends the thread, or a validated data object that needs to be utilized further. Here's a ...

Required attributes not found for data type in TypeScript

When the following code snippet is executed: @Mutation remove_bought_products(productsToBeRemoved: Array<I.Product>) { const tmpProductsInVendingMachine: Array<I.Product> = Object.values(this.productsInVendingMachine); const reducedPro ...

Transforming the Date into Local Time: An Instantaneous Process?

I am currently working with a Kendo UI MVC grid that contains three date columns. These dates, which do not include any time values, are stored in the database as local time rather than UTC. The columns within the grid are defined like so: col ...

Tips for activating a deactivated input field in ReactJS

I am trying to create a feature where my textfields are automatically disabled, but can be enabled for editing by clicking an 'Edit' button. Clicking the button again should disable the textfields and save any edits made. I have experimented with ...

How can I update a CSS class value by utilizing AngularJS variables?

I am currently facing an issue with making my CSS values dynamic. The code I have tried is not functioning as expected. <style> .panel-primary { background-color:{{myColorPanel}} } </style> I came across a similar query on Ho ...

Ways to transfer a state from the child component to the app component

I have 2 different components that contain sub-components within them. In one of these components, I'm trying to figure out how to transfer the click event from the sub-component to another component so that it can render an entirely new component for ...

Trouble with ScrollTo animation on div with adjustable offset top feature - seeking assistance

Having trouble navigating to the correct slide when clicking the right button on the navigation menu. Clicking the menu button displays a list of links. Clicking on a link for the first time will take you to the correct slide, but if you try clicking a dif ...

Displaying React components for a brief duration of time

I have an existing React component where I need to display another component for a specific duration. Upon mounting or data loading of the parent component, the child component should become visible after 1-2 seconds and then disappear after a few more sec ...

The directional rotation plugins of GSAP are incompatible with the plugins of PIXI

I've been experimenting with using directional rotation plugins in combination with pixi.js plugins. Unfortunately, I'm encountering some issues. If you check out the codepen link: https://codepen.io/asiankingofwhales/pen/RyNKBR?editors=0010, yo ...

An error persists in Reactjs when attempting to bind a function that remains undefined

I recently tested this code and everything seems to be working correctly, but the compiler is throwing an error saying 'onDismiss' is undefined. Can someone please assist me with this issue? import React, { Component } from 'react'; c ...

Manage and modify data values

Currently, I am developing a weather forecast app and facing an issue with changing the temperature from Celsius to Fahrenheit upon hovering. Despite my attempts, the changes I make either do not reflect or completely erase the line. I am eager to learn ...

A simple program capable of holding two variables

To create a calculator, I want to implement a process where the user clicks buttons to input numbers into a display box. For instance, clicking 3 and then 2 should display as 32 in the input box. After that, if I click on the "+" button, it should remove t ...

Guide for making an accordion with a close button that is specific to multiple dynamic IDs

I am looking to create an accordion feature. The idea is that when the user clicks on "Show," the text "Show" should be hidden, and the content along with a "Close" button should be displayed. Then, when the user clicks on "Close," the content and "Close" ...

Guide on implementing enums (or const) in VueJS

Seeking help on a seemingly simple task, I am trying to understand how to use "enums" in VueJS. In my file named LandingPage.js, I have the following code: const Form = { LOGIN: 0, SIGN_UP: 1, FORGOT_PASSWORD: 2, }; function main() { new Vue({ ...