JS The function initiates itself without any external trigger

Recently, I've been working on a menu project for the company I'm employed at and everything seems to be functioning correctly. However, there's this peculiar issue that has been bugging me for days and despite extensive research, I haven't been able to find a similar case online.

The project is built using Vue.js and it retrieves data from a database to sort and display on the menu. Unfortunately, I cannot share the entire code here but I'll provide details about the specific function causing trouble and its position within the project.

The problematic function is nested inside another function called "sortMenuItems()" which gets executed when the Vue page loads. This function is defined within the methods section of the "Fview.vue" file, which is a component of the main "Menu.vue" file.

Here is the snippet of code in question, located inside "sortMenuItems()":

let intervalCounter = setInterval(() => {
     counter();
     this.flowerArr = randomNarray(menuItems, 16);
}, 27000);

Essentially, this function houses an interval counter that calls a specific function periodically and updates a variable required for the menu to refresh every 27 seconds. While I am aware that setInterval is not always recommended, it serves the purpose effectively in this scenario. What puzzles me is that this function seems to invoke itself without being explicitly called anywhere else in the project. It creates issues because it starts running automatically when sortMenuItems() is triggered. Despite my best efforts to understand this behavior, I remain perplexed by its mysterious invocation. It doesn't conform to the principles of an Immediately Invoked Function Expression (IIFE). Although the project appears to be functioning smoothly, I have preserved this anomaly as a point of discussion and seek clarification from the coding community through this post on Stack Overflow.

Dependencies for the project:

  • axios
  • concurrently (utilized for a unique cross-origin resource sharing workaround involving a separate JavaScript server)
  • core-js
  • vue
  • vuetify

Answer №1

As Pointy has pointed out, the function I was questioning is not actually a function expression but rather a variable declaration. It functions as a function call expression, and as Pointy eloquently stated: "The variable declared will hold the result of evaluating the entire expression." Therefore, setting the variable to setInterval() allowed it to execute.

I hope my explanation proves helpful for future readers.

A big thank you to Pointy for the clarification!

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 issue with ThreeJS where the camera movement stops working after clicking

Seeking assistance with implementing camera movement in ThreeJS. Despite having no errors, clicking the button does not trigger the camera movement as expected. The function aimed at moving the camera by 200 units in all directions seems to have no effec ...

Guide to dynamically loading webpage content based on URL with JavaScript

During a recent interview, I was challenged to develop a code snippet that would highlight the URL if it contained a specific keyword. Admittedly, I am unsure how to achieve this using JavaScript... ...

AngularJS: Issue with ng-show and ng-click not functioning when button is clicked

I have a specific requirement where I need to display and hide the description of each column in a table when a button is clicked. Here is the visual representation of what I have: the table In my HTML code, I have defined a button with ng-click as a func ...

The HTTP request is malfunctioning in a different location

I'm facing an issue where my code works in the w3schools code editor, but not on localhost or cpanel host. When I try to run it on another host, it gives me a bad request and doesn't return the answer. Here is the code snippet that I am working ...

Retrieve the smallest value from an array of objects using BitGO

Bitgo stores all transactions as objects within a large array. Within the nested .entries, we can identify that the first TX object contains two negative values -312084680 and -4254539, of which I only require the lowest value. My current code successfully ...

How can I use Ajax code to send data to a PHP page and receive the results as a JSON-encoded multidimensional array containing information on each item?

Apologies for the unconventional question title. What I am trying to accomplish is managing two tables in my database: a hotel table (table1) and a room type table (table2). My goal is to allow customers to customize their travel packages by changing hote ...

Android Chrome users experiencing sidebar disappearance after first toggle

Over the past few days, I've dedicated my time to developing a new project. I've been focusing on creating the HTML, CSS, and Java layout to ensure everything works seamlessly. After completing most of the work, the design looks great on desktop ...

Troubleshooting a dysfunctional Vue.js component

I am currently facing a challenge in getting components to function properly. Interestingly, without the component, everything seems to be working fine (as per the commented code). Here is my HTML snippet: <strong>Total Price:</strong> <sp ...

Unending loop caused by nested subscriptions - Angular / RxJS

I am currently implementing a nested subscribe operation, although I am aware that it may not be the most efficient method. Here is an example of what I have: this.route.params.subscribe((params) => { this.order$ .getMa ...

I am struggling to save a second variable that I received into my function

There is a function in my code that takes two values as input, both formatted like this: MyFunction("word1","word2") However, when the function receives the values, it looks like this: MyFunction(test1,test2){} The issue I'm facing is with storing ...

Moving information from Ajax to PHP

I'm experiencing an issue with sending data from AJAX to PHP on the same site, "testpage.php". The PHP script doesn't seem to be displaying the data being sent. Using jQuery/Ajax: <script src="http://code.jquery.com/jquery-latest.js" type="t ...

Replacing old items with new ones: AngularJS now pushes to array in service

I am attempting to update a list in the home.html file and then display the updated list in myOrders.html using ionic and angularjs. The issue I am facing is that whenever I add a new item to the array, it replaces all the previous items with the new one. ...

What are some strategies for implementing dynamic script generation within an AJAX response?

I am exploring a new AJAX design approach where a script is returned to handle and show data. The JSON response below is currently functional, but I would appreciate advice on how to better organize the application for future maintenance. { payload: " ...

Populate a table with data from a different table using JavaScript

On my webpage, I have a grid of selectable divs that are defined by rows and columns. When I select certain divs, it creates what I'll call "table Copy", a three-dimensional table. If I select different elements, another three-dimensional table calle ...

Include the «Load More» option in the data output retrieved using $.getJSON from a Google Spreadsheet

Utilizing Google Spreadsheets as a "Backend", I retrieve the spreadsheet data through Google's JSON-Output () using jQuery's $.getJSON(), process the data by adding values to arrays, and then display the content on the frontend by iterating throu ...

Overcoming Time Limits: What are the best strategies for maximizing performance in my JavaScript code?

I am currently tackling the challenge of solving the Sum of Subarray Ranges problem on LeetCode. Unfortunately, I am encountering a Time Limit Exceeded error which suggests that my code might not be optimized efficiently enough. As I am still learning, I w ...

Develop a regular expression tailored for jQuery validation purposes

I'm working with jQuery validation in my web form and I need to validate a text field with specific criteria: 1. Must contain a number. 2. The letters 'a' or 'A', 'b' or 'B' are allowed after the number. 3. Th ...

What are the steps to turn off the blue hyperlinks on iOS devices?

One example of this issue can be observed in time-formatted text like (00:10 - 10:55) and a time select menu displaying (08:00 AM). I have attempted the following solutions, but none of them have resolved the problem: Mobile Safari/iPhone Mail.app HTML ...

Is there a way to automatically adjust the size of an input field after dynamic spans have been

I am looking to replicate the tagging functionality found on StackOverflow when posting a new question. In this case, spans are dynamically added using an input field located next to them. Here is an example: <div> <div id="multiple-span"&g ...

Prevent script execution if the screen size is below a certain threshold

Snippet of jQuery code: if (jQuery(window).innerWidth() > 568) { jQuery('#boardOfTrustees').masonry({ itemSelector: '.postWrapper', }); } Although this code works fine, I am looking to prevent it from executing or u ...