Using Vue.js method passing an argument and setting a delay with setTimeout function

I'm struggling to understand why this particular code is functioning as it should.

data: {
    return {
        userMinerals: 0,
        mineralsLimit: 1000,
        miners: 0,
        superMiner: 0,
        minerPrice: 10,
        superMinerPrice: 100,
        minersLimit: 10
    }
}
methods: {
    counter() {
        setInterval(() => {
            this.userMinerals += this.miners;

            if(this.checkLimit(this.userMinerals, this.mineralsLimit)) {
                this.userMinerals = this.mineralsLimit;
            }
        }, 100);
    },
    addMiner() {
        if (this.userMinerals >= this.minerPrice) {
            this.miners += 1;
            this.userMinerals -= this.minerPrice;
            this.counter();
        }
    }
}

However, when I attempt to pass parameters into the counter() function, the code suddenly stops working.

methods: {
    counter(typeOfCredits) {
        setInterval(() => {
            typeOfCredits += this.miners;

            if(this.checkLimit(this.userMinerals, this.mineralsLimit)) {
                typeOfCredits = this.mineralsLimit;
            }
        }, 100);
    },
    addMiner() {
        if (this.userMinerals >= this.minerPrice) {
            this.miners += 1;
            this.userMinerals -= this.minerPrice;
            this.counter(this.userMinerals);
        }
    }
}

Despite observing in the console that typeOfCredits is being incremented correctly, it fails to update the value in the view. Any assistance would be greatly appreciated. Thank you.

Answer №1

When working with parameters, it's important to note that you cannot reference a parameter and expect it to be changed outside of its scope. However, you can pass a reference to an object that has the ability to change something outside of its own scope.

var $this = this;
this.counter({
    get() { return $this.userMinerals },
    set(val) { $this.userMinerals = val }
});

This means that you can use the counter function like this:

    counter(typeOfCredits) {
        setInterval(() => {
            typeOfCredits.set(typeOfCredits.get() + this.miners);

            if(this.checkLimit(this.userMinerals, this.mineralsLimit)) {
                typeOfCredits.set(this.mineralsLimit);
            }
        }, 100);
    },

Check out this jsfiddle link for more information.

Answer №2

When working with the typeOfCredits parameter in a function, keep in mind that parameters are passed by value. This means any modifications made to it within the function will only affect its local scope.

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

Tips for implementing a distinct texture on child elements through traversal techniques

My current dilemma involves working with an object that I've loaded using THREE.ObjectLoader(). This object consists of various elements, resembling a simple box made up of panels and sticks. My goal is to assign different textures to specific child ...

Send the innerHTML content to the data layer in Tag Manager

As a newcomer to HTML and CSS, I apologize if this question has already been asked. I am currently working on implementing tags for a new website that keeps track of the number of times sections are viewed on a page. The section names are stored in a var ...

How to Create an Interactive JavaScript Drop Down List for Displaying and Concealing Divs

Looking for some assistance in combining a chained drop-down list with the functionality to show/hide a specific div based on selection. I've come across solutions for each separately, but struggling to merge the JavaScript code (not my strong suit as ...

The dropdown menu repeatedly opens the initial menu only

My script fetches data from a database to populate a table with one row for each member. Each row contains a dropdown list with the same class and ID. Although I attempted to open and close the dropdowns using specific codes, I am facing an issue where onl ...

Utilize a CSS selector to target all deleted nodes using the MutationObserver in the HTML5 API

Is there a way to retrieve all removed nodes from the DOM that have specific classes using CSS selectors? Below is an example of how it can be done with some complexity, but is there a simpler and more general approach? new MutationObserver(mut =& ...

Image Filter: Only Display Selected Images, Not All

I have designed a Filter Image Gallery where all images are initially displayed when the page loads. There are four different tabs available - Show all, Nature, Cars, and People. However, I want to change this default behavior so that only Nature filter i ...

How can we efficiently execute text searches on a large scale by utilizing static index files that are easily accessible online

Looking for a lightweight, yet scalable solution for implementing a full text search index in JavaScript using static files accessible via HTTP? Seeking to make about 100k documents searchable online without breaking the bank on hosting costs like Elastics ...

Creating dynamic animations in React/Redux that respond to user actions

As I near the completion of my first React+Redux application, I am eager to incorporate animations throughout the different sections of the project. However, I have found that the existing solutions do not quite meet my expectations. The ReactCSSTransition ...

Ways to display data from specific columns using their names in a pair of dropdown lists

I am faced with the challenge of creating a drop-down menu containing column names from a database table. In addition, I need to implement another drop-down menu. My goal is to have the values of the selected column name from the database table displayed ...

Express.js - display the complete information

Trying to display an array of objects (highcharts points) is giving me some trouble. Instead of the actual data, I'm seeing [object Object]. It seems that JSON.stringify() doesn't play well with HTML. util.inspect also doesn't work as expe ...

Use Javascript's JQuery library to apply functionality to a newly inserted and cloned

I am facing an issue while trying to implement JQueryUI's DatePicker on a node. It works perfectly fine for all the existing nodes, but when I use the clone function to add new nodes, it doesn't seem to apply as expected. Here is the function th ...

Tips for keeping the app on the same route or page even after a refresh

I'm currently diving into the world of React and am in the process of constructing a CRUD application. I've successfully created multiple pages that utilize react-router-dom for navigation with authentication. The pages are accessible only to log ...

What is the best way to share dynamic content from a DIV or SPAN element on WhatsApp using jQuery?

I’ve been attempting to share the text content of a specific DIV on WhatsApp, but so far I haven't been successful. My goal is to only share a portion of the document (specifically the contents of showques). Below is the code snippet I've been ...

Authenticating and authorizing a client-side web application with a Remote NodeJS API integrating Passport.js

Displayed in the diagram below, there is an independent API Project operating on a server with a specific port, for example 3001, and a Web App running on a different server with another port, like 3002. https://i.sstatic.net/ovvAZ.png Running on port 30 ...

The JavaScript code in angularJS fails to execute properly after importing angular.js

As a newcomer to AngularJS, I'm puzzled by why the code below isn't functioning as expected. The browser is not loading the file 'myjavascriptcode.js'. When I place "<script src="./myjavascriptcode.js"></script>" before imp ...

What are the best methods for utilizing rating stars in PHP?

Currently, I am incorporating the star rating system from Rating Stars. I am working on creating a PHP table and dynamically populating it with records. In this table, there will be a column dedicated to displaying these stars. Each record is saved as a n ...

Step-by-step guide on transferring form data from an Ionic application to parse.com MBaaS through the REST API

Today is my first day with Ionic/Angular, and I'm diving in out of necessity. I've been using tutorials and documentation to create a demo/test app that submits data to the Parse.com MBaaS service. However, I seem to be stuck somewhere and clue ...

The trio of PHP, AJAX, and HTML work in harmony to display separate sections of a webpage from the same site within

I am currently using a PHP file with my output function that includes do_header and do_body, among others. Within the body function, I have three div tags: div 1, div 2, div 3. Div 1 contains the other two positioned on the left and right of it. In div 2 ...

Convert a String to JSON using either JavaScript or jQuery

Currently, I am developing a JavaScript animation script and I am aiming to allow individuals to define behavior declaratively within the HTML. This is the format I envision for my HTML: <div data-animation="top: 600, left: 600, opacity: 1, start: 0.2 ...

Choose to either push as a single object or as individual items

I have a quick question that I'd like to get some clarity on. Can someone explain the distinction between these two code snippets: export const addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ...