Setting a default value in an arrow function

Currently, I am working on a section of code that renders a simple loading bar.

const smallSpinner = document.getElementById('spinner-small').getContext('2d');
let pointToFill = 4.72;
let cw = smallSpinner.canvas.width; //Returns canvas width
let ch = smallSpinner.canvas.height; //Returns canvas height
let diff;

let fillSmallSpinner = (startingPointParam = 0) => {
    diff = ((startingPointParam / 100) * Math.PI * 2 * 10);

    smallSpinner.clearRect(0, 0, cw, ch);

    smallSpinner.lineWidth = 5;

    smallSpinner.strokeStyle = '#d40511';

    /* smallSpinner.textAlign = 'center';
    
     smallSpinner.font = "25px monospace"; 
    
     smallSpinner.fillText(no + '%', 50, 55); */ //uncomment this if you need percent progress inside spinner

    smallSpinner.beginPath();

    smallSpinner.arc(50, 50, 40, pointToFill, diff / 10 + pointToFill);

    smallSpinner.stroke();


    if (startingPointParam >= 100) {
        clearTimeout(fill);
    }
    startingPointParam++;
}

let small = setInterval(fillSmallSpinner, 50);

The issue arises when "startingPointParam" is passed as a function parameter instead of being defined as a normal variable like this:

let startingPointParam = 0;

It seems to work perfectly fine with the predefined starting point at 0%, but it fails when I try to make it more versatile by passing the starting point as a function parameter. Can anyone provide insights on how to resolve this?

Answer №1

Each instance when setInterval schedules a call to fillSmallSpinner, it continuously receives its default parameter.

A more frequently used approach involves encapsulating the function in a manner that maintains the scope of the desired variable:

const startFiller(callback, interval = 50, start = 0) {
    let current = startPoint;
    let timer = setInterval(() => {
        callback(current++);
        if (current >= 100) {
            clearTimeout(timer);
        }
    }, interval);
});

startFiller(fillSmallSpinner);

You can then eliminate any existing timer-related logic from your fillSmallSpinner function. This method also offers the advantage of Separation of Concerns - in case you opt for a different function to display your spinner, it no longer needs to manage timers.

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

Is it possible to use getJSON to retrieve a value from an HTML tag ID that has already been displayed on a webpage? How about using json_decode

Is there a way to retrieve the value using the HTML tag ID after an HTML page has been rendered? For example, how can I access the date value using the td_date in my JavaScript function? Below is the code snippet that populates the data on the page: listS ...

Starting the selection process using AngularJS and ng-repeat

My challenge is to have a pre-filled option in a select-box using ng-repeat with AngularJS 1.1.5. However, the select box always starts off with nothing selected and an empty option, which I don't want. It seems to be a side effect of not having anyth ...

Retrieving data from a remote source repeatedly based on user selections on a single page

In my current project, I am utilizing next js to build a web application. One of the pages in this app has the following structure: <page> <component_1> This component fetches data from a remote server using `getInitialProps` (alternat ...

The absence of a backslash in the JSON string is noticed upon uploading it to the database

After using the JSON.stringify() method in JavaScript to convert my JSON object into a JSON string, I insert it into a database via AJAX posting to a PHP file. $("#saveToDatabase").click(function(){ var place = searchBox.getPlaces(); var locati ...

Finding the index of a column based on a continuous sequence of values can be achieved by following these

Consider this sequence of numbers representing components on a page: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Every set of 3 numbers makes up a page, with indexing restarting for each new page. Essentially, it follo ...

capture the alteration of text within an input field

Currently, I am utilizing the Joomla calendar feature to select a date. The HTML code for this functionality is displayed below. When you click on the image, a calendar will pop up allowing you to choose a date. Once selected, the popup closes and the date ...

There seems to be an issue: [ng:areq] - Please visit the following link for more information: http://errors.angularjs.org/1

Hey there! I'm in need of some assistance. Just started learning Angular and tried setting it up like this. This is the structure of my files: AboutController.js function AboutController( $scope ){ $scope.data = { "data" : { "name ...

The various sections of my website are neatly tucked away under one tab, only revealing themselves to users as they click on each individual tab

My recently published website is experiencing a strange issue. When the site loads, all contents including paragraphs and videos from other pages are displayed under one tab (the HOME tab). However, once any other tab is clicked, the issue fixes itself. Yo ...

react native is not updating the view even though the state has been changed

Upon opening my component, I am looking to retrieve Assets from a Media Folder (which is currently functional) and then pass them along to another component. However, the issue arises when launching the app for the first time, as the "listOfAssets" state a ...

Customizable form fields in AngularJS

Consider the scenario of the form below: First Name: string Last Name: string Married: checkbox % Display the following once the checkbox is selected % Partner First Name: Partner Last Name: [Submit] How can a form with optional fields be created in Angu ...

What strategies can be used to effectively manage multiple asynchronous requests?

I have two requirements: one is to load an image (which will take a long time on the backend server), and the other is to perform an AJAX request. I would like it to be structured like this: $.when( [perform image loading] [perform ajax request] ).t ...

How can one access a specific element by its id that is located within an ng-template in Angular 6?

I have a question regarding accessing a button element inside an ng-template tag using its id in the TypeScript file. How can I accomplish that without encountering undefined errors? This is what I have tried so far: HTML <ng-template #popup > ...

Get only the text content from a hyperlink using Tinymce-4

Within tinymce.activeEditor, I currently have this line of innerHTML code (part of a ul-list): <li><a href="#">Important words</a></li> When I place the caret within the sentence "Important words," and click a button with the foll ...

What is the best method for combining ajax and php to perform a redirect?

I'm facing an issue with redirecting users from the login page to their profile page. I'm using ajax to validate the form, but upon successful login, the profile page is displayed on top of the index page. How can I ensure that the redirection ha ...

I am experiencing an issue with my date filter where it does not display any results when I choose the same date for the start and end dates. Can anyone help me troub

Having an issue with my custom filter pipe in Angular. When I select the same dates in the start and end date, it doesn't display the result even though the record exists for that date. I've noticed that I have to enter a date 1 day before or ea ...

Unravel JSON using JavaScript on the web

I encountered an issue while running this code and trying to decode it: var data = JSON.parse({"forms":[{"url":"example.com/example","name":"example"}]}) document.getElementById("name").innerHTML=data.forms.name Instead of the expected value, the returne ...

Stopping the spread of popup alerts: A comprehensive guide

I'm having trouble explaining this in English;-) Whenever I select an option, an alert pops up for each choice and I don't know how to stop it. Step 1: Choose the "aaaa" option, for example 1111 alert ... Step 2: Choose the "bbbb" option, for ...

Utilizing NextJS to retrieve cookie data within React components

Currently, I am working with a Next.js frontend and an Express backend. For authentication, I am utilizing cookies and have set up protected routes using Next.js middleware. The next step in my project involves accessing the cookie response within React ...

Convert JavaBeans sources into a JSON descriptor

I'm in search of a tool or method to analyze standard JavaBeans source code (featuring getters and setters) and create json descriptors using tools like grunt or ant, or any other suitable option. Here's an example: FilterBean.java: package com ...

What is preventing me from displaying the results on the webpage?

Currently, I am utilizing Express alongside SQLite and SQLite3 modules. However, upon running the server, the data fails to display on the initial request. It is only after a page refresh that the data finally appears. I attempted a potential solution by ...