What is the reason for this basic callback running before the setTimeout function?

Interesting behavior is observed in this code, where 'output 2' is logged before 'output 1' due to the setTimeout function.

const func1 = () => {
  setTimeout(() => {
    console.log('output 1');
  }, 3000);
};

const func2 = () => {
  console.log('output 2');
};

func1();
func2();

Despite using a callback in the second snippet, the execution order remains the same. The question arises: why does func2 execute before func1? Is there a way to ensure that func2 runs after func1?

const func1 = () => {
  setTimeout(() => {
    console.log('output 1');
  }, 3000);
};

const func2 = () => {
  console.log('output 2');
};

const main = (a, b) => {
  a();
  b();
};

main(func1, func2);

Answer №1

Why does func2 execute before func1?

Actually, func1 does execute first.

  1. Func1 initiates a setTimeout function
  2. Func2 performs a log action
  3. After 3 seconds, the callback function assigned to setTimeout is triggered

If you want Func2 to run after step 3, then you must call it at the end of the callback function specified in setTimeout.

Answer №2

When JavaScript encounters a setTimeout function, it stores the functions with the provided timeout duration (in this case 3 seconds) in the call stack but continues to execute the functions below it immediately. This is why you may see the output of the second function before the first function. To ensure that the first function is executed before the second function, you can use promise chaining as shown in the example below:

 return new Promise(function(resolve, reject) {
     setTimeout(() => {
        console.log('output 1');
        resolve();
     }, 3000);
 }).then(function(result) {
     console.log('output 2');
 });

I hope this explanation helps clarify things. Please feel free to correct me if I am mistaken.

Answer №3

Simply put -

Function 2 does not wait for the timer set by function 1 to complete before running.

func1();
func2();

As both functions are executed, function 1 initiates the timer while function 2 starts logging out immediately.

After 3 seconds, function 1 finally logs out.

Your alternate code snippet functions in a similar way.

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

Is it necessary to use `top` or `parent` when utilizing local scripts in an iFrame?

Is it possible to eliminate the use of top or parent in iFrame localized scripts, as the title suggests? Upon examining the screenshot below, I encounter a "not defined" error unless I include top or parent as a prefix to my function call. test(); does n ...

Verification response parameter not received from Google Authentication Express

I've been working on implementing a "sign in with Google" feature for my localhost website. Despite receiving the POST request, I noticed that it lacks the credential parameter. I'm unsure if this issue lies within the code or the API configurati ...

Having trouble with the dropdown menu in Bootstrap?

I'm having trouble creating a responsive dropdown menu. When I click on the dropdown items, nothing happens. Here's the code: <div class="navbar-header"> <button type="button" class="navbar-toggel" data-toggel="collapse" data-target="#m ...

Positioning Div at the Bottom of a Interactive Flip Card Using Bootstrap 4

My current project features a creative flip image card created using bootstrap and js. On the back of the card, there is a title, a main text body, and a few small additional pieces of information. My goal is to have these three small bits of information a ...

Encountering challenges with concealing a div element

As I'm setting up a table, I want to hide it immediately after creating it without affecting the DOM. Then, when the user selects from a dropdown menu, I show the table and everything works fine. However, the issue arises when I visit the page for the ...

What triggers the onmouseout event to occur?

Is the event triggered continuously whenever the mouse is not hovering over the element? Or is it a one-time action when the mouse exits the element? This distinction is crucial for me to determine when the mouse pointer leaves the element, while only wa ...

The double click functionality does not seem to be functioning within the Backbone View

I am trying to detect double click event within a Backbone view var HomePage = Backbone.View.extend({ initialize: function(){ this.render(); }, render: function(){ var template = _.template($('#app1').html()); ...

What sets xhr.response apart from xhr.responseText in XMLHttpRequest?

Is there any difference between the values returned by xhr.response and xhr.responseText in a 'GET' request? ...

Is there a way for my component to function seamlessly within another component without the need for redundant code?

Is there a way to avoid repeating code when using my component inside another component? For example, in the file NextPage.js, the <LogoutButton/> component does not perform its function. How can I ensure that the <LogoutButton/> behaves the s ...

Tips for preventing the use of website URLs as variables in jQuery ajax() calls:

Having some trouble. For example: $(document).ready(function () { $("#btnSend").click(function () { var noti_p = { url: "Pusher_Controller.ashx", data: "&appname=" + $("#selt1").val() + "&title=" + $("#title"). ...

Using JavaScript to enhance event handling for a `select` element in a progressive manner

I have an advanced <select> element in my HTML. It is structured like this: <ul> <li></li> <li></li> ... </ul> In the current setup, a click event handler is attached to each individual li element. If the ...

ERROR: Expo TaskManager Notifications [TypeError: Attempting to call an undefined function (near '...Notifications.presentLocalNotificationAsync...')]

I'm currently trying to figure out how to send notifications whenever a task is triggered, but I keep encountering an error that I can't seem to fix. Here's the error message: TaskManager: Task "background-fetch" failed:, [TypeError: unde ...

Transform nested properties of an object into a new data type

I created a versatile function that recursively converts nested property values into numbers: type CastToNumber<T> = T extends string ? number : { [K in keyof T]: CastToNumber<T[K]> }; type StringMap = { [key: string]: any }; const castOb ...

What are some methods for transferring the state variable's value from one component to another in React?

I have the following scenario in my code: there is a Form.js component that interacts with an API, stores the response in the walletAssets state variable, and now I want to create a separate Display.js component to present this data. How can I pass the v ...

Display a button only when hovering over it

Seeking assistance for a simple task that is eluding me at the moment. I am currently using scss and trying to make a button only appear when hovered over. The button is hidden in the code snippet below, nested within a block alongside some svgs. Any hel ...

Confirm the session validity before invoking the web service function from an ajax function triggered by clicking a button

I am experiencing a complex issue. On a page, users input data and then click on a button to save all the parameters into a JSON object. After saving locally, they click another button which triggers an ajax method that calls a web service method on the sa ...

Difficulty encountered in assigning a value to a variable when utilizing an async function in Node.js

While attempting to retrieve the jwtauthtoken from the user and passing it to a function called getUserId() in the imported JavaScript file, I encountered an issue where the returned value was undefined instead of the decoded ID. The getUserId() function ...

What is the best way to insert a record into the rth column of the nth row in a table

In the table I'm working with, there are 6 columns and only 5 of them have data filled in. The last column is currently empty for all rows. I am now trying to populate the last column of each row with some data. Can someone guide me on how to use a f ...

Can anyone guide me on troubleshooting the firebase import error in order to resolve it? The error message I am encountering is "Module not found: Error:

When attempting to import the 'auth' module from my 'firebase.js' file, I encountered an error. I used the code import {auth} from "./firebase", which resulted in the following error message: Error: Unable to locate module &a ...

Exclude specific outcomes within a nested document in MongoDB

I have a situation where I need to query a list of items and only retrieve the ones that correspond to a specific ID in the provider_cost_dict. Essentially, if I input providerId = 10001, then only the items with a matching entry in the provider_cost_dict ...