Accessing global variables after using the setInterval function can be tricky. Sometimes, despite setting the variable, it may still return undefined or

I have a typescript class where I am encountering some issues with accessing the starttime and count in the setInterval function. Even though I have set their values before, I am seeing undefined and NaN results. How can I resolve this problem?

startTimer() {
 this.startTime = new Date();
 this.count = 100;
 console.log("STARTTIME: " + this.startTime); //RESULT: Mon Dec 17..etc
 console.log("COUNT: " + this.count); //RESULT: 100
    this.timer = setInterval(function () {
      console.log("STARTTIME: " + this.startTime); //Undefined
      this.count += 1;
      console.log("COUNT: " + this.count); //NaN
     }, 1000);
 }

Answer №1

Consider using arrow notation in place of traditional functions.

(as recommended in the resource)

this has often been a source of confusion in JavaScript. As someone once rightly stated, "Dealing with JavaScript can be frustrating as it frequently misinterprets the value of this". Arrow functions address this issue by inheriting the context of this from the surrounding scope.

Hence, implement it like so:

setInterval(() => {  // <-----
  console.log("STARTTIME: " + this.startTime); 
  this.count += 1;
  console.log("COUNT: " + this.count); 
}, 1000);

View on Stackblitz for live example

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

Utilizing Typescript, create a customized dropdown with react-bootstrap for a tailored user

I've been working on incorporating a custom toggle drop-down feature based on the example provided on the react-bootstrap page, using Typescript and react functional components. Below is the code snippet for my component: import React from &apos ...

The imported variables are of a union type

In my nextjs project, I developed a customized hook to determine if a specific container is within the viewport using the intersection observer. Here's the code for the custom hook: import { useEffect, useRef, useState } from 'react'; cons ...

Tips for applying styles to components generated dynamically in Angular 5

Requirement My goal is to place dynamically generated components in a container with rows and columns, the number depending on user input. Initially, each component occupies 1 row and 1 column but can be resized as needed. When a new component is added, i ...

Determine the selected choice in a mat-select with multiple selections made

Can you please help me find out which option was recently selected by the user in the selectionChange event for a multi-select, like the one shown below? My goal is to detect when the user clicks on the 'All' option, and ignore that specific sel ...

Services that are not configured as singleton instances

In my view, I am utilizing a file upload component multiple times. Each uploading file is managed by a service that handles its metadata. However, when I add files to one component, all the components begin updating instead of just the intended one. Is it ...

Execute a Typescript function where parameters are passed to another function

In my coding project, I came across a situation where I needed to write a method in Typescript. This method should allow me to run some checks and, if those conditions are met, return the result of another method. What I want is to pass a method along with ...

What is the best way to invoke a TypeScript function within a jQuery function?

Is it possible to invoke a TypeScript function within a jQuery function? If so, what is the correct approach? Here is an example of my component.ts file: getCalendar(){ calendarOptions:Object = { height: 'parent', fixedWeekCount : ...

Error occurs when attempting to filter data through input text pasting in Angular

Currently, I am working on a web application that utilizes the Angular framework and angularfire2. The issue I am encountering is related to the data filter functionality not functioning correctly when pasting copied text. Interestingly, it works perfectly ...

Replicate the process of transferring table rows to the clipboard, but exclusively copying the contents

Currently, I am attempting to copy a paginated table to my clipboard by referring to this guide: Select a complete table with Javascript (to be copied to clipboard). However, the issue lies in the fact that it only copies the data from the first page. In ...

Angular Tutorial: Modifying the CSS transform property of HTML elements within a component directly

Currently, I'm in the process of developing an analog clock for a project using Angular. My challenge is figuring out how to dynamically update the sec/min/hour handlers on the clock based on the current time by manipulating the style.transform prope ...

Tips for ensuring proper dependency regulations in javascript/typescript/webpack

In essence, I am in search of a method to limit dependencies, similar to how one would manage different projects (libraries) in Java or C#. Think of it as friend or internal access modifiers. I'm considering various approaches to accomplish this (suc ...

`Why does the npm test command in vue2 source code fail with the error "Type ... is not assignable to type ..."?`

After cloning the Vue source code from github using git clone, I proceeded to install dependencies by running yarn. However, when I ran npm test, the test failed. https://i.sstatic.net/aZXBg.png Does anyone have insight on why this error occurred and how ...

Customize your Joi message using the .or() method

I'm attempting to personalize a message for the .or() function in Joi, similar to this: https://i.stack.imgur.com/68dKx.png The default message from Joi is as follows: Validation Error: "value" must contain at least one of [optionOne, optionTwo] ...

Exploring Angular: A Guide to Localisation and JSON

Looking at my JSON database structure below: { "users" : { "-Kowtg5yyK-DTIz91cQ8" : { "language" : "en", "uid" : "kNyDJnktxyakL6owhGd1rruGACb2", "userName" : "admin" } }, "localisation" : { "login" : { "en" : "Log ...

Instantiate a TypeScript object and establish its type by setting restrictions derived from an input object

I have been working on creating a function that takes an object A: { [key: string]: string | undefined } as its parameter. The goal is to generate a new object B with all properties from A, converting each string property to type number, and each string | ...

Angular 6 allows for the use of radio buttons to dynamically enable or disable corresponding fields

Here is the HTML code for a row containing radio button selections: <div class="form-row"> <div class="col-md-3 mb-3"> <div class = "form-group form-inline col-md-12 mb-3"> <div class="form-check form-check-inl ...

Guide on troubleshooting *.ts files in an ionic 2 project using Chrome's inspect devices feature

After successfully creating my Ionic 2 application for Android using the command "ionic build android", everything seems to be working fine. I have been debugging the app by using Chrome inspect devices, but now I am facing an issue. I am trying to debug ...

What is the best way to adjust the color of the colon within my timer digits using a span element?

I am facing an issue with my timer where the span that was created to display a colon between the numbers does not change color along with the timer digits. I attempted using var colon = document.getElementById(":"); but it still did not work as expected. ...

Utilizing Angular 5: Display a Loading Indicator while Searching using Async Pipe

As I work on incorporating a search field with async in Angular 5, I want the loading indicator to appear when the user starts typing in the search box and disappear once the results are fetched. However, following this approach led to the loading indicato ...

"Unlock the secret to effortlessly redirecting users to a designated page when they click the browser's back

So I'm facing the challenge of disabling the browser back button on multiple routes and sending requests to the backend is resulting in inconsistent behavior. I don't want to create a multitude of similar API requests each time. Currently, I have ...