Unusual situation involving the override of a function pointer variable

Let's explore a straightforward scenario:

(function x(){
  var foo = function(){
    console.log('foo is alive!');

    // set 'foo' variable to an empty function, using a delay
    setTimeout(function(){
      foo = function(){};
    },0);
  }

  foo();
  // calling 'foo' again, after it should be an empty function
  setTimeout(foo,100);
})();

When you execute this code in your console, it will print foo is alive! twice. I am puzzled about why the foo variable isn't replaced with the empty function. The timeout callback recognizes foo as a variable pointing to the function.

Dull backstory for this inquiry:
This test case is a simplified version of a more intricate situation involving AJAX callbacks instead of the timeout present in this example.

Answer №1

By calling the setTimeout() function immediately and passing it foo(), you ensure that foo() is available later when setTimeout() runs.

Here's a quick demo to illustrate this concept:

setTimeout(function () {
    foo();
}, 100);

(Check out the live example here: http://jsfiddle.net/0p7fgsso/)

In this scenario, the foo() function is only accessed after it has been defined as an empty function. As a result, nothing will be logged to the console.

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

Comparing a series of smaller strings to a larger string for testing purposes

My website has an array filled with bot names. Whenever a user or bot visits the site, I retrieve the user-agent and want to check if any of the values in my array are present in it. var bots = [ "twitterbot", "linkedinbot", "facebookexternalhit", ...

Is there a way to simulate a KeyboardEvent (DOM_VK_UP) that the browser will process as if it were actually pressed by the user?

Take a look at this code snippet inspired by this solution. <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <script> $(this). ...

Is there a way to confirm that the content of two files is identical?

Currently, I am utilizing mocha/supertest/should.js for testing a REST Service. When I make a request to GET /files/<hash>, it returns the file as a stream. I am seeking guidance on how to use should.js to assert that the contents of the file are i ...

How do you populate a dropdownlistfor in ASP.NET MVC after a form

My issue is that <form> @Html.DropDownListFor(x => x.City, provinces, "--Select City--", new { @class = "dropdownList" }) @Html.DropDownListFor(x => x.district, Enumerable.Empty<SelectListItem>(), "--Select district--") < ...

In Nextjs, it is possible to extend a page just like creating a nested switch in react-router-dom. This functionality

After spending some time using React, I recently decided to experiment with NextJS. Currently, I am working on a dashboard project that includes a side navigation menu, which will be used across multiple pages. In ReactJS, I typically create a nested switc ...

Having trouble getting the Javascript/jQuery listener to function properly with Underscore.js templates

I've been working on developing a webapp using underscore.js for creating templates. However, I've encountered an issue when trying to render a basic template like the one below: <div id="container"></div> <script type=& ...

Discover the pixel width of a Bootstrap grid row or container using JavaScript

How can I calculate the width of a Bootstrap grid row or container in pixels using JavaScript? I am working with Aurelia for my JavaScript project, but I'm open to solutions in standard JS (no jQuery, please). Looking at the Bootstrap documentation, ...

code for handling window.location.href error

Continuing from the previous question, I am facing an issue with redirecting a form to an action while using Ajax. Despite my attempts to add a redirect in the Ajax function, I keep encountering errors and getting the wrong URL. The desired redirection is ...

Steps for creating a personalized query or route in feathersjs

I'm feeling a bit lost and confused while trying to navigate through the documentation. This is my first time using feathersjs and I am slowly getting the hang of it. Let's say I can create a /messages route using a service generator to GET all ...

Implementing mouse hover functionality in a VueJS component within a Laravel application

I am facing an issue with my mouse hover functionality while working on Laravel. The Vue file I am using is located in resources/js/Dashboard.vue I have attempted to replace v-on:mouseover with @mouseover but the problem persists. When I hover over the ...

Creating a multipart/form-data request using JavaScript/jQuery

After much searching and experimentation, I have been trying to understand the process of constructing a request to be sent using something similar to $.ajax({ contentType: "multipart/form-data", type: "POST", data: ...

Best return type for a webservice triggered using jQuery but not requiring any data to be returned

I am currently working on a web service that utilizes several methods. These methods do not have significant impact on the client side as I call them using jQuery/ajax. My main concern is regarding the recommended return type. Typically, I would return JS ...

Delay in Response of OnTextChanged Event in ASP.NET

The functionality is there, but it doesn't respond immediately. It only works when I click on something. I attempted using the onkeyPress method as well: <asp:TextBox ID="txtWriter" runat="server" onkeyPress="txtOnKeyPress" ></asp:TextBox& ...

Utilize npm to incorporate external JavaScript libraries into Meteor 1.3

Trying to integrate the OpenSeadragon library into my Meteor app has been a bit challenging. After successfully installing it via npm using meteor npm install openseadragon, I found that the OpenSeadragon docs only offer an example using the script tag. T ...

What is preventing me from sending back an array of objects with an async function?

Working with node.js, my goal is to retrieve a list of bid and ask prices from a trading exchange website within an async function. While I can successfully log the object data using console.info() within the foreach statement on each iteration, when attem ...

React Router integration problem with Semantic UI React

Just diving into ReactJS and encountering a problem with using "Menu.Item" (from Semantic UI React) and React Router. I won't include my imports here, but rest assured they are all set up correctly. The constructor in my "App.jsx" looks like this: ...

Deactivate the Submit button when the database field has been populated

My form includes a submit button. The Submit button should be disabled if the "price" for a specific product is already filled: PHP Code <?php $host="localhost"; $username="root"; $password=""; $db_name="ge"; $con=mysqli_connect("$h ...

Executing functions across modules in node.js

I need assistance with two of my modules: var client = require('./handlers/client.js'); var server = require('./handlers/server.js'); server.createClient() The client module: var client = function(){ console.log("New client"); ...

Enable the feature for users to upload images to a specific folder within the Chrome extension without the need for

I need to implement a feature in my Chrome extension that allows users to upload images directly to a specific folder named "upload" without needing a submit button. <form action="/upload"> <input type="file" name="myimages" accept="image/*"> ...

Is nesting ajax calls in jQuery a clever strategy?

I currently have this ajax call: $.ajax({ url: "misc/sendPM.php", type: "POST", data: data, success: function(stuff) { if (typeof stuff == "object") { var err = confirm(stuff.error); if (err) { ...