When a function is passed as an argument in Javascript code, the setTimeout function may behave in unique ways

After running the code below, I noticed an interesting behavior:

setTimeout(() => console.log('first'), 0)
console.log('second');

As expected in JavaScript's asynchronous nature, the output was as follows:

second
first

However, when I modified the first argument of the setTimeout() function like this:

       //notice the ()=> part is removed
        setTimeout(console.log('first'), 0)
        console.log('second');

The order of output changed to:

first 
second

It seems that by removing the ()=> part, JavaScript started behaving synchronously again.

Any insights on this unexpected result?

Answer №1

When you utilize

setTimeout(console.log('first'), 0)
, the value returned by console.log('first') is seen as undefined. This means that an undefined function reference is passed to setTimeout.

As a result, the console.log('first') statement is executed synchronously and no asynchronous behavior is observed in the output because the function reference supplied to setTimeout is undefined.

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

The functionality of selecting all items in v-select does not result in saving all of them

I'm currently working on integrating a select all button into the v-select component of Vuetify. The issue I am facing is that even though I can use the button to select all options, when I attempt to save, not all items are saved. However, if I manua ...

Sending an array with a specific identifier through JQuery ajax

I'm facing an issue where I am sending an array of values via jQuery AJAX to my servlet. However, the servlet is only picking up the first value in the array, even though there are more elements present. $.ajax({ type: "POST", url: "mySer ...

Incorporating Information into an Array as a State Object within React.js

Hey everyone, I've hit a bit of a roadblock and I could really use some assistance. I'm trying to figure out why I keep getting an error when attempting to push user input into my array. Can someone take a look at my code and offer some insight? ...

Customize the filename and Task Bar name for your Electron app when using electron-packager

My application uses electron packager to build the app on Mac. Here is my package.json configuration: { "name": "desktop_v2" "productName": "desktop v2", "version": "1.0.0", "license": "MIT", "scripts": { "build": "node --max_o ...

send a message to all clients using socket.io

I am having trouble figuring out how to broadcast a message from the client or another NodeJS file to all clients. While I was able to send messages to the server successfully, I am not able to reach every other client. Server code: var io = require(&ap ...

What is the most effective method for synchronizing data with HTML5 video playback?

I am currently developing a program that retrieves data from an android application and plays it back on a web browser. The android app allows users to record videos while logging data every 100ms, such as GPS location, speed, and accelerometer readings, i ...

The Map/Reduce function is producing incorrect results because of null values, causing me to receive NaN or erroneous

I am ready to delve into another Map/Reduce query. Within my database, I have a collection named "example" which is structured like this: { "userid" : "somehash", "channel" : "Channel 1" } The Map/Reduce functions I am using are as follows: var map = f ...

Setting up a nodejs application on a web server

As a newcomer to NodeJS, I am currently learning how to create a sample app using this technology. I have successfully tested it on my localhost, but now I am facing issues when trying to host it on a public server. var http = require('http'); ...

Utilizing AJAX to add information to jQuery data tables without taking advantage of their pagination and advanced features

The jQuery datatables plugin is a useful tool for adding filters, pagination, and search functionality to web applications. I have personally integrated it with my Laravel project to organize and display data effectively. Recently, I decided to enhance th ...

Removing duplicate entries from a dropdown menu can be achieved by implementing

As a newcomer to the world of PHP PDO, I've learned that the database connection should be in a separate PHP file. However, after spending an entire day trying different things, I'm still facing issues. I suspect that the duplicate entries are a ...

Using Ruby instead of Javascript in lessc

My CSS is compiled in a node application using lessc. LESS was installed via NPM. When I check the current version of lessc --version it shows lessc 1.3.3 (LESS Compiler) [Ruby] 2.3.2 How can I change it to display lessc 1.3.0 (LESS Compiler) ...

Struggling to get JQuery timing events to function properly?

Encountering timing issues with the events in my self-made simon memory game. Experimented with setTimeout but struggling to figure out which events to time and the appropriate duration for them to be distinguishable. $('#play').click(function( ...

Can a middleware function in Node.js be executed asynchronously?

I've developed a middleware function to validate user access tokens (JWT) ... in case the JWT has expired, I automatically generate a new access token using the user's refresh token (if it is also valid). As my user base grows, I anticipate that ...

What does dist entail?

I am currently utilizing gulp to create a distribution folder (dist) for my Angular application. After consolidating all the controllers/services JS files and CSS, I am now faced with handling the contents of the bower folder. In an attempt to concatenat ...

JavaScript accordions failing to open

I've encountered an issue with my website that includes JS accordions. Strangely, they are not opening on the live site, but they function properly on Codepen. I checked the console in Chrome and found no error messages, however, when I looked at the ...

Creating Scalable Vector Graphics without utilizing identifiers

For instance, if we have defs and rect defined separately, we would typically use an ID. <defs> <linearGradient id="MyGradient"> <stop offset="0%" stop-color="#000" /> <stop offset="100%" stop-color="#fff" /> ...

Getting rid of the Horizontal Scroll Bar

Having trouble with a persistent horizontal scrollbar in the "section3__container" container despite attempts to adjust size and overflow settings. Need assistance in removing this unwanted feature. <html lang="en"> <head> <m ...

What are the best practices for creating a contemporary website that functions effectively on IE7?

After creating several websites for my clients, I discovered that they are not functioning well in IE7. Unfortunately, there is still a small percentage of people using IE7. Can anyone suggest a super quick solution to fix this issue? Feel free to recomm ...

Incorporate npm libraries into vanilla JavaScript for HTML pages

Attempting to incorporate an npm package into plain JS/HTML served using Python and Flask. <script type="module"> import { configureChains, createClient } from "./node_modules/@wagmi/core"; import { bsc } from "./nod ...

Learn how to automatically navigate to another page upon successfully creating an account and setting a value in the Firebase database

I am working on a system where, after successfully creating an account and setting a value in Firebase database, the user will be redirected to another page. Currently, I have managed to navigate to the next page but I am facing an issue with setting the ...