What is the best way to use setInterval with multiple objects?

Subject:

Here is an example of JavaScript code:

var User = function(data){
  this.name = data.name;
  this.delay = data.delay;
  this.say();
}

User.prototype.say = function(){
  _self = this;
  setInterval(function(){
    console.log(_self.name);
  }, this.delay * 1000);
}

var u1 = new User({name: "user1", delay: 10});
var u2 = new User({name: "user2", delay: 15});

The objects u1 and u2 return user2.

How can we make it so that user1 returns after 10 seconds and user2 returns after 15 seconds?

Answer №1

The reason for this issue lies in the concept of closures. Contrary to what you might think, a new copy of _self is not created for each setInterval because the variable is in the global scope. As a result, the last instance created replaces the previous ones.

Here's a suggested solution:

var User = function(data){
  this.name = data.name;
  this.delay = data.delay;
  this.say();
}

User.prototype.say = function(){
  var _self = this;
    setInterval(function(){
      console.log(_self.name);
  }, this.delay * 1000);
}

var u1 = new User({name: "user1", delay: 10});
var u2 = new User({name: "user2", delay: 15});

Each invocation of the anonymous function establishes a fresh local scope, distinct for every closure formed within it. Consequently, each scope possesses its own value for _self when you prepend var to it.

It would be beneficial to review the documentation on Bind() as well.

Answer №2

It appears that the setInterval method is referencing a cached copy of _self. To resolve this, you can try the following:

let _self = this;

Answer №3

Avoid the use of global variables. Instead, declare _self as a local variable:

let _self = ...;

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 React DOM element undergoes mounting and unmounting on each render cycle when it should be simply altered/updated

As per the React documentation, callback refs are invoked during both component mounting (with the DOM element's value) and unmounting (with null): When a React component mounts, the ref callback is triggered with the actual DOM element, and when it ...

I'm experiencing some issues with the JavaScript setTimeout function - can anyone help troubleshoot

in my quest to find a way to hide the notificationBar without the use of a button and using XX.hide() oncomplete, I stumbled upon a javascript snippet <script type="text/javascript> jQuery(function() { bar.show(); setT ...

Tips for properly implementing ng-hide and ng-show across various sections of your single page application

Currently working on a Single Page Application (SPA). I've included some buttons in the side navigation with the intention of displaying different content when they are clicked. However, I encountered an issue where using ng-hide and show didn't ...

How is it that this JavaScript task does not trigger an error: const a = (1, 2, 3, 4);

let x = (5, 6, 7, 8); console.log(x); let y = 5, 6, 7, 8; console.log(y); In the example above, x will be assigned a value of 8, while the second line will result in an error. What is the reason behind the success of the first assignment? How does it qua ...

Could one potentially generate new static files in Nextjs without needing to rebuild the entire app?

After recently beginning to utilize NextJs' getStaticProps feature, I have found that the static files generated at build time are quite impressive. However, my content is not static and requires updates without having to rebuild the entire app each t ...

What is the best way to eliminate a JSON header?

Here is the JSON data I have: { "folder": [ { "$": { "id": "471841542", "name": "Manajemen Pemasaran", "description": "", "user_id": "186868958", "shared": "1", "shared_l ...

Utilizing a React hook within an event listener

I have developed a custom hook for playing audio in react, here is the code: "use client"; import { useEffect, useState } from "react"; export const useAudio = (url: string) => { const [audio, setAudio] = useState<HTMLAudioE ...

What could be causing the issue preventing me from updating my SQL database through AJAX?

$(document).ready(function(){ $('.button').click(function(){ var clickBtnValue = $(this).val(); var ajaxurl = 'functions/delivered.php', data = {'action': clickBtnValue}; $.post(ajaxurl, da ...

Troubleshooting Proxy.php issues in conjunction with AJAX Solr

Attempting to access a Solr 4.5.0 instance located on a private server, http://12.34.56.789:8983/ The application resides at this web server address, http://www.mywebapp.com To facilitate accessing the JSON object within the Solr instance, I decided to ...

Combine React 17 with webpack 5 and babel-plugin-react-css-modules, enabling the use of CSS modules with stylename functionality

I am in the process of setting up a new React application using the latest technologies available, including React 17, Webpack 5, and other essential modules. My goal is to implement CSS modules utilizing the styleName concept with the help of babel-plugi ...

Trouble obtaining AJAX result using onClick event

As a newbie to AJAX, I am still trying to grasp the concept. My task involves using an AJAX call to extract specified information from an XML file. Even after carefully parsing all tag elements into my JavaScript code, I encounter a problem when attempting ...

Interact with multidimensional arrays using Vue JS

Is there a way to access properties within objects nested inside multidimensional arrays when using v-for with VueJS? var arr =[{"fruit": {"fruitName": "apple"}, "vegetable":[{"vegetableName": "carrot" }]}]; I am attempting to display it in the following ...

What is the best way to consistently position a particular row at the bottom of the table in AG-grid?

I have successfully implemented a table using AG-grid. Here is the code snippet: .HTML <ag-grid-angular #agGrid style="width: 100%; height: 100%; font-size: 12px;" class="ag-theme-alpine" [rowData]=&quo ...

Is it best practice to display a DIV once it is no longer visible after scrolling down?

Upon opening my website, an information box (div) appears on the screen. However, when the user scrolls down and the box is no longer visible, I want it to always appear in the top right corner while scrolling. I have figured out how to keep it visible at ...

The JQuery script has not been initialized, causing the function to not activate

I keep encountering this error message: Uncaught ReferenceError: toggleOptionsVisibility is not defined at HTMLSelectElement.onchange Here's the HTML code I'm working with: <div> <label asp-for="Type"></label&g ...

What is the method to design a file upload feature without a specific form using JavaScript?

I am currently working on a form that handles file uploads using jQuery and AJAX. The goal is to upload the files individually as JSON containing base64 data. Rather than uploading all the images at once, I want each image to be treated as if it were in it ...

What is the best way to incorporate a Bootstrap modal for delete confirmation before proceeding with data deletion through a POST request?

As a beginner in web development, I am currently learning how to use JavaScript, Express, Node, and Mongoose. In my app, I want to display a confirmation modal using Bootstrap before deleting any data, only proceeding with the deletion when the user clicks ...

Having trouble installing npm package in Angular project

After cloning my project from GitLab, I encountered an issue while trying to install the NPM packages. When I ran npm install, an error popped up: https://i.stack.imgur.com/WNT5s.png Upon checking the log file, I found the following error message: 3060 ...

Is there a way to change the color of the menu button to white if the points are not visible?

I have created CSS to style the menu's color and make the buttons change color based on different actions. However, I also want the buttons to match the colors of the points on the map. To achieve this, I set the background color in JavaScript when ge ...

Leveraging arrays generated from two separate MySQL queries for dual selection functionality with JavaScript

I have successfully populated the first HTML select with results from the first query. Now, I would like to store the results from the second query in either a Json file or XML and then use plain javascript (not jQuery) to populate the second HTML select ...