Feeling lost about arrow functions in JavaScript

Here is the code I am currently using to increment the value of intVariable using window.setInterval.

var Arrow = (function () {
    function Arrow() {
        this.intVariable = 1;
        this.itemId = -1;
        this.interval = 25;
    }
    Arrow.prototype.activateTimer = function () {
        if (this.itemId === -1) {
            window.setInterval(this.showTimer(), this.interval);
        }
    };
    Arrow.prototype.showTimer = function () {
        this.intVariable += this.interval;
        console.log(this.intVariable);
    };
    return Arrow;
}());
var arrow = new Arrow();
arrow.activateTimer();

When I use the line below, the showTimer function is only called once:

window.setInterval(this.showTimer(), this.interval);

However, when I change it to:

window.setInterval(() => this.showTimer(), this.interval);

It works flawlessly.

I'm curious why it worked using an arrow function and would appreciate some insight.

Answer №1

One option is to use the function reference directly, without using parenthesis.

window.setInterval(this.showTimer, this.interval);

If you opt for a function call, however,

window.setInterval(this.showTimer(), this.interval);
//                               ^^

you will be inserting the result of the function call rather than the function itself.

Alternatively, when you do

window.setInterval(() => this.showTimer(), this.interval);

you are including a function without executing it at that moment.

Answer №2

It's important to provide a function to the interval, not just the return value of the function.

When you use

window.setInterval(this.showTimer(), this.interval);
, what actually happens is:

var returnValue = (function () {
  this.intVariable += this.interval;
  console.log(this.intVariable); // You get your log for once
})() // -> null
window.setInterval(returnValue/*null*/, this.interval);

Then, setInterval attempts to call null after each time interval, without throwing an error in the console.

However, if you use an arrow function like () => this.showTimer(), it becomes:

var returnValue = function() {
  this.showTimer();
} // -> Function
window.setInterval(returnValue/*Function*/, this.interval);

In this case, you're providing a function to the interval.


If you forget to bind your function to the correct scope, you may encounter issues accessing specific values. Make sure to bind the function to the current object scope to avoid confusion with global scopes.

When using () =>, the anonymous function automatically connects its scope to the object, eliminating the need for extra binding.

For a proper solution, consider the following code:

    var Arrow = (function () {
        function Arrow() {
            this.intVariable = 1;
            this.itemId = -1;
            this.interval = 25;
        }
        Arrow.prototype.showTimer = function () {
            this.intVariable += this.interval;
            console.log(this.intVariable);
        };
        Arrow.prototype.activateTimer = function () {
            if (this.itemId === -1) {
                window.setInterval(this.showTimer.bind(this), this.interval);
            }
        };
        return Arrow;

}());
var arrow = new Arrow();
arrow.activateTimer();

For a demonstration, check out this JSFiddle link.

Answer №3

let timer = setInterval(() => this.displayTimer(), this.timeInterval);

functions similarly to

let timer = setInterval(function() {this.displayTimer()}, this.timeInterval);

setInterval(this.displayTimer(), this.timeInterval);
doesn't function because you should only pass the this.displayTimer without immediately invoking it

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

Adding the "input-invalid" class to the input doesn't take effect until I click outside of the input field

When the zipcode field is updated, an ajax call is made. If there are no zipcodes available, I want to mark it as invalid by adding the "input-invalid" class. However, the red border validation only appears when clicking outside of the input field. Is ther ...

Resolving Problems with Ion-Split-pane in the Latest Versions of Angular and Ionic

There seems to be a perplexing issue with the ion-split-pane element that I just can't wrap my head around. Once I remove the split-pane element, the router-outlet functions perfectly fine. The navigation is displayed after a successful login. The on ...

react-vimeo not firing onPause and onPlay events

I am facing an issue with triggering props when playing a Vimeo video on my webpage. Here's a snippet of my code: import Vimeo from '@u-wave/react-vimeo'; const handleVimeoProgress = (data: any) => { console.log('Progress:' ...

Retrieve data from each URL listed in a JSON array using React

My json file structure was as follows: [ { "name": "google", "route": "/google", "url": "www.google.com" }, { "name": "bing", "route": " ...

Delay the axios get request in the useEffect

Working with React JS, I have implemented a useEffect hook to request data from a database via an Express server when the page renders. However, if the server is down, the app will continue to make thousands of requests until it crashes. Is there a way to ...

Next.js is unable to identify custom npm package

My unique custom package structure looks like this: package.json Posts.js Inside Posts.js, I have the following code: const Posts = () => { return <div>List of posts</div> } export default Posts; After publishing to the GitHub Package ...

Restrict the PHP generated Json response to display only the top 5 results

I need to modify my search bar so that it only displays the top 5 related products after a search. public function getProducts() { if (request()->ajax()) { $search_term = request()->input('term', ''); $locatio ...

Error: Value of incoming scope in Angular Directive is not defined

When working in html, I passed an object into a directive like this: <lcd-code ldcCode="{{ detail.program.ldcCode }}"></lcd-code> The value of detail.program.ldcCode is "PSIH"... However, in the Directive, it is showing up as undefined: var ...

Can one look through a div to the one beneath it by moving the cursor?

Hey there! I have a unique question for you. I've been trying to achieve a specific effect where two divs are stacked on top of each other, and the content of the lower div is only revealed in a certain area around the cursor. Is it possible to make o ...

Is it considered proper to initialize an empty array within the data object of a Vue.js component?

For my component, I am in need of multiple empty arrays and predefined objects. The data object structure provided below seems to be effective for my purpose. However, I am uncertain if this is the optimal pattern and whether it might lead to unforeseen co ...

Enabling or disabling select input based on the selected option in a previous select dropdown

My goal here is to customize a select input with 3 options: Sale, Rent, Wanted. Based on the selection, I want to display one of three other select inputs. For example, if "Sale" is chosen, show the property sale input and hide the others. However, when su ...

What steps can be taken to have Eslint/Prettier report errors and warnings within a CI environment?

Recently, I encountered an issue with my Vue app where I am using Eslint with Prettier. Even though I have set up a Github action to check the code style, running npm run lint -- --no-fix only logs the warnings and does not cause the workflow to fail. I r ...

Passing parent form controls from an Angular 4 FormGroup to a child component

I have implemented Angular Reactive Forms FormGroup and FormArray in my project. The issue I am facing is related to splitting my form fields into child components and passing the parent form controls to them. I expected this to be a straightforward proces ...

Issue with jQuery.off when using a dynamic function name

I am currently implementing a modular pattern for writing my JavaScript code and it has been an enjoyable experience! However, I have encountered a challenging situation. My Namespace structure looks like this: var settings, handlers, objects, Namespace ...

Failed to import due to an error from the downloaded dependency

I'm encountering an import error in the @react-three module of my downloaded package. ./node_modules/@react-three/drei/node_modules/troika-three-text/dist/troika-three-text.esm.js Attempted import error: 'webgl-sdf-generator' does not cont ...

Retrieving JSON information from a PHP script with AJAX

I am currently experiencing an issue with my PHP script, 'getNews.php'. Despite working correctly in the terminal and returning the expected data, I am encountering difficulties when trying to retrieve this information through JavaScript. <?p ...

"422 (Unprocessable Entity) Error When Submitting a Form in Rails Application

I recently delved into the world of ruby on rails a few days back. My current challenge involves transferring data from html tags to a ruby function using ajax. Below is the error message that has been giving me trouble: POST http://localhost:3000/ajax/o ...

Turn off logging functionality in a Node.JS environment

I am looking to turn off logging for specific environments in my Node.JS application using Express. Would the following method be considered the most optimal way to disable logging within Node.JS applications? if(process.env.NODE_ENV == "production") { ...

What is the best way to display pages with different states in ExpressJS?

Here is a code block that I have: var express = require('express'); var newsRouter = express.Router(); newsRouter.get('/:news_param', (req, res) => { let news_params = '/haberler/' + req.params.news_param; req.ne ...

Three.js is currently rendering a blank canvas in pure white

After following the tutorial at , my browser only displays a white window. I attempted separating the files into js and html, but no luck. What I have already tried: experimenting with adding/deleting the nomodule parameter in the script tag utilizing a ...