`The function `setTimeout` throws an error when passed as a string.`

Here are two pieces of code that may look identical, but one works properly:

function hideElement(obj) {setTimeout(function() {obj.style.display = "none";}, 20);}

On the other hand, the second one results in error: obj is not defined:

function hideElement(obj) {setTimeout('obj.style.display = "none"', 20);}

What could be causing this difference?
P.S.: Take a look at this example

Answer №1

The solution can be found within the concept of function closures, which offer a more in-depth explanation.

In the initial scenario, the obj variable becomes encapsulated when the anonymous function is created. As a result, when the function is executed, the captured reference to obj allows access to the style property without any issues.

Conversely, in the second scenario, there is no closure due to the fact that the string undergoes evaluation through eval while being nested inside setTimeout. According to the information provided on the Mozilla documentation, this execution takes place within the global context:

Since string literals are assessed at a global level, local symbols from the environment where setTimeout() was invoked will not be accessible during the code evaluation of the string.

Considering that the global context does not include the obj variable, an error indicating it as "undefined" emerges.

Answer №2

obj is limited to the scope of the dismiss() function and its contents. The initial statement creates a function that can access it, while the second statement operates outside of that scope and cannot access it.

Answer №3

As stated in the official documentation:

When setTimeout() is called, the code within it runs in a separate environment compared to the function that invoked it. This results in the this keyword referring to the window (or global) object rather than the original function's this value.
:

Both examples illustrate how the scope of timeout code is linked to the global context, specifically window.

In the first scenario, the specific context is insignificant because obj.style.display is not assessed until the timeout activates. By that point, obj retains its initial value set by dismiss, ensuring smooth execution.

In contrast, the second example executes the code immediately, meaning that obj remains undefined within the global window scope (or if defined, it may not align with expectations). Essentially, this leads to the following situation:

function dismiss(obj) {setTimeout(function ()  { undefined = "none" }, 20);}

Answer №4

The accurate code should appear as follows:

function hideElement(element) {setTimeout(element.style.display = "none", 20);}

Be sure not to add extra single quotes at the start and end of element.style.display = "none", as it will convert it into a string.

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

Unpacking arguments in Typescript functions

I have a function to update todo items in the database, like this: async function update({id, ...todoInfo }: ITodo) { const db = await makeDb() const foundTodo = await db.collection('todos').updateOne({ _id: transformId(id) }, { $set: { . ...

What sets apart npm correlation-id from uuid?

Can you please explain the distinction between the uuid and correlation-id npm packages? It seems that correlation-id actually utilizes the uuid package internally.. When would you recommend using correlation-id over uuid? Important: I am not utilizing ...

The canvas surpasses the boundaries of the grid layout

Trying to design a grid layout with 3 columns of content, alongside an .overlay div featuring a particles.js canvas. Having trouble? See my Codepen here: https://codepen.io/radzak/pen/MVQVPQ The goal is for the grid to always occupy 100% of the screen, t ...

When attempting to click the "New" button in a lightning datatable to add a new row, an error

Having trouble adding a new row when clicking the New Button in a Lightning Data table. I've created a lightning-button in HTML and called the method in JavaScript. However, when I click the New button, I'm getting an error message saying Undefin ...

Begin by executing the initial commit task with Git through Gulp, followed by performing the

I am currently working on a project and I am trying to use gulp to commit and push to git. However, I am encountering an issue where the push task is not waiting for the commit task to complete before running... Can anyone assist me with this? I want to s ...

The issue of HTML form not displaying within a Java servlet environment

While following a basic tutorial to learn Java servlet programming in Eclipse, I encountered an issue with the browser not rendering the submit button in the HTML form. Despite reviewing the code multiple times, making small modifications, and even double- ...

Problem with IE off-canvas scrolling

Currently, I am facing an issue with the scrolling functionality of an off-canvas sidebar on my Joomla 3 website. It seems to be working fine in Chrome and Firefox, but when it comes to Internet Explorer, the visible scroll bar refuses to move when attempt ...

Exploring and listing the key-value pairs from several arrays within an object

My inquiry pertains to the following function: function loadConfigurations(configs){ console.log(configs); } The 'configs' object received by the loadConfigurations function contains two properties --two arrays named "assigned" and "unassign ...

Receiving information within an Angular Component (Profile page)

I am currently developing a MEAN Stack application and have successfully implemented authentication and authorization using jWt. Everything is working smoothly, but I am encountering an issue with retrieving user data in the Profile page component. Here ar ...

Saving the current $index from an ng-repeat loop to a database row (with row numbers 1.1, 1.2, 1.3) using AngularJS

Currently, I am developing the index page functionality for a book. i.e : 1.1 1.1.1 1.2 1.2.1 In this setup, 1.1 and 1.2 are the parent ng-repeats, while 1.1.1 and 1.2.1 are the child ng-repeats. My goal is to store these numbers ( ...

Different ways to resize an image in various sizes without relying on PHP thumb

I have developed an admin panel for managing reservations of charter, yacht and other vehicles. I am looking for a solution to upload only one image per vehicle and resize it in multiple sizes without relying on the phpthumb library due to its slow loadi ...

Tips on displaying an array of elements as a <Dialog> within a <List>

I am currently developing a <ElementList> component that is designed to accept an array of elements through props and create a <List>, with each <ListItem> representing an element in the array. I have also included a separate component ca ...

An array is not just a mere collection of elements

I have an object that resembles an array var items = [ { started_time: 2017-05-04T12:46:39.439Z, word: 'bottle', questionId: '161013bd-00cc-4ad1-8f98-1a8384e202c8' }, { started_time: 2017-05-04T12:47:26.130Z, word: &apo ...

Instructions for importing a CSV file into PostgreSQL with Node.js

Just dipping my toes into the world of node js. I've got a csv file sitting on my local system that I'm eager to upload to my local PostgreSQL Database using node js. Here's what I've been experimenting with: var csv = require(' ...

I am not encountering any error messages, but when I attempt to click on the form, the mouse cursor does not change to the expected form type

While there are no errors showing up in the Chrome Developers Error code, I am facing an issue with my form where the text fields are not visible. It should be a simple task, but it has turned into a headache for me. I would greatly appreciate any help i ...

Troubleshooting the Ng2-Charts Linechart to display all values instead of just the first two

Starting a new Angular application with the Angular-CLI (beta 22.1) has presented an issue when adding test data (5 values) to a chart. The scaling appears incorrect, displaying only the first two values stretched across the entire length of the graph (ref ...

Arrange floating elements in a three-column layout

Can anyone help me with a CSS solution to make boxes with different heights stack underneath each other neatly, similar to Tetris? Here's my code: CSS #page .equipeBox{ float:left; width:280px; padding:10px; margin:10px; backgro ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

Tips for maintaining an open side menu

I'm having trouble keeping the side menu open when a user clicks on one of the child menu items. Ideally, I want section 1 to display section 2 content when hovered over, and keep both sections open even when section 2 is clicked. The only time they s ...

State management at its core with integrated functionalities

I'm exploring different ways to manage application state within Angular 18 using its built-in features. Would it be effective to start with a simple service that utilizes dependency injection (DI)? As someone new to Angular 18, I'm a bit confuse ...