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

Using Javascript, verify if a given URL is legitimate and commences with "http://" or "https://"

I need to validate the authenticity of my URLs, ensuring they begin with either http:// or https://. Here is the regular expression (RegExp) I have been using: private testIfValidURL(str) { const pattern = new RegExp('^(https?:\\/&bsol ...

Using a callback function with jQuery in a focus event

Is there a way to ensure that a callback function inside a focus() is only played once while the element has focus? For example, in the code snippet below, the alert('ok') will continue to be triggered as long as the textarea maintains focus. Is ...

Ways to extract all hyperlinks from a website using puppeteer

Is there a way to utilize puppeteer and a for loop to extract all links present in the source code of a website, including javascript file links? I am looking for a solution that goes beyond extracting links within html tags. This is what I have in mind: a ...

Looking to use regex to search through a webpage's text content written in JavaScript

I am struggling with the re.search function and how to use it effectively. I have a block of text/javascript that I need to extract in order to convert it to json using json loads. $(function() { $product = $('#product-' + 12272257171); ...

jquery is showing up in the browserify bundle.js file, however, it is not functioning properly

Currently, I am trying to follow a brief tutorial on how to use Browserify. Despite following the instructions precisely, jQuery seems to not be working properly when bundled. Specifically, the button element in my app.js code is not appended to the body. ...

Access all the properties of an object within a mongoose record

My database contains a collection of documents that are structured using the mongoose and express frameworks. Each document follows this schema: const userSchema = new Schema({ firstName: { type: String }, lastName: { type: String }, email: { t ...

Ways to create a group label to modify various textboxes when a click event occurs

Is it possible to change multiple textboxes with corresponding labels after a click event? Issue: The current output only displays the value of the last textbox. $(function () { $('a.edit').on('click', function (e) { e.pre ...

Using jQuery, you can enclose a string of text with HTML tags easily

This specific content within the span is being dynamically created by PHP. However, I am uncertain how to efficiently target the text string in order to begin using jQuery. <!-- input: --> <span class="price">RM1,088.00 Annually + RM10.00 Se ...

What could be causing my Express server to return a 404 error when trying to submit the form, all while failing to display any console

Having trouble setting up multi-user sessions similar to Google Docs, but my server file seems unresponsive. I've double-checked my fetch function and ensured it is accurate, yet no changes are occurring. Even console.logs from the server file command ...

What is the best way to calculate the number of squares required to completely fill a browser window in real-time?

I am creating a unique design with colorful squares to cover the entire browser window (for example, 20px by 20px repeated both horizontally and vertically). Each square corresponds to one of 100 different colors, which links to a relevant blog post about ...

Multer is experiencing difficulties in uploading files, yet it is not displaying any error messages

When setting up an application to create courses with images, I encountered an issue while using multer for image uploading. Despite adding multer to my route with upload.single('images'), the uploaded images were not appearing in the designated ...

What is the correct way to update an empty object within the state using setState?

I'm currently dealing with a state that looks like this: this.state={ angles:{} } I need to know how to use setState on this empty object. Specifically, if I want to add a key and value inside my empty 'angles'. How can I achieve that? Fo ...

Discover the process for finding a Youtube Channel Name with querySelectorAll

OUTPUT : Console URL : https://www.youtube.com/feed/trending?gl=IN document.querySelectorAll('a[class="yt-simple-endpoint style-scope yt-formatted-string"]')[0].innerText; document.querySelectorAll('a[class="yt-simple-endpoi ...

The Magnificent jQuery Widget Factory's _trigger Instance

When utilizing the _trigger function to initiate events, I often come across a recurring issue that I struggle to fully comprehend. The problem arises when there are multiple instances of my widget on the same page. In such cases, the most recently instan ...

After repeated attempts to initialize and destroy, Froala encounters issues when loading a textarea via Ajax

Whenever an EDIT button is clicked to update some Blog Data, it triggers an Ajax call that brings up a textarea for Froala and initiates the initialization process. This sequence works smoothly initially, but after a few cycles of edit/submit (1, 2, or 3 o ...

Navigating through async functions in an Express.js router

Encountered a lint error indicating that Promises cannot be returned in places where a void is expected. Both functions [validateJWT, getUser] are async functions. Any suggestions on how to resolve this issue without compromising the linter guidelines by u ...

How to deactivate or modify the href attribute of an anchor element using jQuery

My HTML code looks something like this: <div id="StoreLocatorPlaceHolder_ctl07_ctl00_ctl00_pager_ctl00_ctl00_numeric" class="sf_pagerNumeric"> <a href="http://www.domain.com/store-list">1</a> <a href="http://www.domain.com/sto ...

Is there a way to transform a stringified array into an array in JavaScript if I do not have access to the original string?

Recently, I encountered a challenge where I had an array of items enclosed within "", and not '' (if that distinction matters): "['item 1', 'item2', 'item 3']" I am interested in converting it to ...

Simple yet perplexing JavaScript within an Angular directive

In the tutorial, the author explains that each element in the stars array contains an object with a 'filled' value, which is determined as true or false based on the scope.ratingValue received from the DOM. directive('fundooRating', fu ...

Switching Tabs When a Button is Clicked

I am currently using a guide from the link provided to learn how to create tabs: http://www.w3schools.com/howto/howto_js_tabs.asp. function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClass ...