The setInterval method in Typescript/Javascript is unable to invoke other functions

I have a situation where I need to call the function callMe() every 1000 ms. While this setup is functioning as expected, I am encountering an issue when trying to call another function from within callMe(). The error message I am receiving is:

uncaught TypeError: this.sortTargets is not a function

Here is my class variable:

private intervalId : any;

The code and functions in question are:

constructor () {
    this.intervalId = setInterval(this.checkLabelConflicts, 1000);
  }

  private sortTargets() {
    console.log("hello world");
  }

  private checkFunction()  {
  this.sortTargets();
}

It seems that I am unable to call other functions from within the intervaled function. I have even tried rearranging the code, moving the constructor to the bottom, but it seems like there might be a declaration missing error. If anyone has a solution that does not involve setInterval (such as workers/threads), I would greatly appreciate the explanation.

Have a great Monday!

Answer №1

How can I ensure the correct `this` context is accessed within a callback function?

constructor () {
    this.intervalId = setInterval(this.checkLabelConflicts.bind(this), 1000);
  }

  private sortTargets() {
    console.log("hello world");
  }

  private checkFunction()  {
  this.sortTargets();
}

I had to use .bind(this) to solve the issue.

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

Searching for the precise error name being thrown in MySQL using Node.js

Currently, I am in the process of constructing a server using node.js (express) and mysql felix. The issue I am facing is that occasionally I encounter a duplicate error when running a certain query. I have exhausted all of my attempts to handle this err ...

I'm experiencing some issues with my scene in ThreeJS - the HDR background isn't displaying, and my cube

<style> body { margin: 0; } </style> <script async src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afcadc82c2c0cbdac3ca82dcc7c6c2dcef9e8199819c">[email protected]&l ...

Tips for extracting a value from a currently active list item's anchor tag with JQuery on Mapbox API?

Currently, I am attempting to extract the value from a forward geocoder that predicts addresses while a user is typing. My goal is to then send this value to a form with an id of "pickup". However, I am encountering difficulties in capturing the li > a ...

Make sure link opens in the same window/tab

Currently, I am utilizing the Open Link in Same Tab extension on Google Chrome. This extension can be found here. The purpose of this extension is to ensure that all links open in the same window/tab, which is necessary for touch screen kiosk left/right s ...

Tips for creating a Next.js "Link" component with an optional "href" property

I've created a custom React function using typescript for the Next.js Link component. The "href" property is necessary for the "Link" to be used anywhere, so it couldn't be utilized as a button that functions as a submit button in forms. import N ...

Synchronize numerous PouchDB databases with a single CouchDB database

After reading the PouchDB documentation, I learned that sync occurs between a local database and a remote CouchDB database. Currently, I am working on developing a native application that includes a unique local database for each user (multiple databases) ...

When we typically scroll down the page, the next section should automatically bring us back to the top of the page

When we scroll down the page, the next section should automatically bring us back to the top of the page without having to use the mouse wheel. .bg1 { background-color: #C5876F; height: 1000px; } .bg2 { background-color: #7882BB; height: 1000px; } .bg3 ...

The GitHub process is ongoing and not ending

I have developed a GitHub workflow that utilizes a node script. To test it, I set it up to run on manual trigger. Below is the code snippet of my workflow file: on: workflow_dispatch: inputs: logLevel: description: 'Log level&apos ...

button for resetting the zoom in Highcharts

Attempting to manipulate the visibility of the Zoom Button on a highstock chart through x axis zooming with the navigator feature enabled. The default behavior seems to disable the button in this scenario. While there are functions allowing for display, I ...

Converting a JSON object to a string and replacing specific text can be achieved by following

I have a JSON object that I need to convert to a string and then perform substring replacements using JQuery var data = JSON.stringify(object); data = data.replace("meat", "vegetables"); console.log(data); However, when I attempt to run this code, I enco ...

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

Tips for creating multiple popups using a single line of JavaScript code

I am new to JavaScript and I am attempting to create a popup. However, I am facing an issue in opening two divs with a single line of JavaScript code. Only one div opens while the other remains closed despite trying various solutions found on this website. ...

Discover the combined type of values from a const enum in Typescript

Within my project, some forms are specified by the backend as a JSON object and then processed in a module of the application. The field type is determined by a specific attribute (fieldType) included for each field; all other options vary based on this ty ...

How can we replicate the 'setTimeout' feature in Node.js without causing any interruption to the event loop?

After extensive research, I have been trying to figure out how to implement non-blocking code in Node.js. However, all the examples I have come across are tied to functions that already have built-in callbacks. Therefore, I attempted to create my own funct ...

React is failing to display JSX elements within a map function

Currently, I am attempting to run a loop and then display JSX content: While the console.log displays the correct data, the return statement is not rendering the HTML content. const StaticTable = (props) => { const [data, setData] = useState({}); ...

How can I prevent Heroku from automatically running the script with 'npm start'?

I am currently in the process of developing a server-based application that utilizes automated scripts, also known as "bots," within a cloud environment. I have set up Heroku Scheduler to execute one of these scripts automatically, as illustrated in Figure ...

Manage Datatables: Efficiently toggling the display of multiple rows in a loop

This specific inquiry pertains to the Datatables plug-in for JQuery. I am working with an HTML table that contains entries in 3 languages: en, ru, fr. When a language is selected, the entries in the other two languages should be hidden. For instance, if E ...

Altering CSS styles through JavaScript or jQuery

Exploring Options After investigating the use of .css() to manipulate CSS properties of specific elements, I came across a website showcasing the following CSS: body, table td, select { font-family: Arial Unicode MS, Arial, sans-serif; font-size: ...

Adjust the column count in mat-grid-list upon the initial loading of the component

My goal is to implement a mat-grid-list of images with a dynamic number of columns based on the screen size. Everything works perfectly except for one small glitch – when the grid first loads, it defaults to 3 columns regardless of the screen size until ...

What is the best way to merge imported types from a relative path?

In my TypeScript project, I am utilizing custom typings by importing them into my .ts modules with the following import statement: import { MyCoolInterface } from './types' However, when I compile my project using tsc, I encounter an issue wher ...