How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval().

Here's the snippet of my code:

export class SmileyDirective
{

FillGraphValues()    
{
    console.log("The FillGraphValues function works as expected");      // this works
}

MyTimer()
{
    console.log("The timer is functioning properly");      // this works
    this.FillGraphValues();          // this does not work
    FillGraphValues();               // this does not work
}

draw()
{
    this.FillGraphValues();    // this works

    setInterval(this.MyTimer, 1000);
}
} 

The application crashes with either:

"this.FillGraphValues is not a function"

or

Cannot find name 'FillGraphValues'. Did you mean the instance member 'this.FillGraphValues'?

I even tried:

setInterval(function(){MyTimer()}, 1000);

and

setInterval(function(){this.MyTimer()}, 1000);

But unfortunately, none of these approaches worked.

Your assistance would be greatly appreciated! :)

Answer №1

Perhaps this approach could be successful: setInterval(() => {this.MyTimer()}, 1000);

thus, the code would appear as follows:

export class SmileyDirective {

    FillGraphValues() {
        console.log("FillGraphValues works");      // this works
    }

    MyTimer() {
        console.log("timer works");      // this works
        this.FillGraphValues();          // this DOES work
    }

    draw() {
        this.FillGraphValues();    // this works

        setInterval(() => { this.MyTimer() }, 1000);
    }
}

var obj = new SmileyDirective();
obj.draw(); 

this conversion produces clean output:

define(["require", "exports"], function (require, exports) {
    "use strict";
    var SmileyDirective = (function () {
        function SmileyDirective() {
        }
        SmileyDirective.prototype.FillGraphValues = function () {
            console.log("FillGraphValues works"); // this works
        };
        SmileyDirective.prototype.MyTimer = function () {
            console.log("timer works"); // this works
            this.FillGraphValues(); // this does not work
        };
        SmileyDirective.prototype.draw = function () {
            var _this = this;
            this.FillGraphValues(); // this works
            setInterval(function () { _this.MyTimer(); }, 1000);
        };
        return SmileyDirective;
    }());
    exports.SmileyDirective = SmileyDirective;
    var obj = new SmileyDirective();
    obj.draw();
});

The critical element to focus on is

 var _this = this;
            this.FillGraphValues(); // this works
            setInterval(function () { _this.MyTimer(); }, 1000);

essentially maintaining the context by saving the this variable in closure and utilizing it when the setInterval triggers the function.

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

What is the method for retrieving array values from an attribute?

I am currently developing an Angular 6 application and I need to pass and retrieve array values dynamically through attributes. Here is the code snippet I have used for this purpose: HTML: <ul class="list-unstyled" id="list" [attr.parent_id]="123"> ...

The functionality of the Bootstrap toggle button seems to be malfunctioning

I'm having trouble with the toggle button in my Bootstrap code. When I resize the window, the toggle button appears but clicking on it doesn't do anything. This is my first time using Bootstrap, so I might have made some silly mistake. Any assist ...

Add the hue value from Hue into the Chromajs HSL state value

My objective is to dynamically change the background color of a div based on user input. I plan to assign the user's input as the value of the state key hue, and then set another state key called color to hold the HSL representation of the hue using C ...

The express app is configured to send a 301 status code when Supertest is used, and it is

Hello, I am currently utilizing supertest to test the functionality of my Node.js express server application. My goal is to accomplish the following: let request = require('supertest'); let app = require('./server.js'); request(app). ...

Place a hook following the storage of a variable in the device's memory

Within a component, I am facing the following situation: const [home, setHome]=useState(false) if(home){ return(<Redirect push={true} to="/" />); } setItem("isRegistered", resquest[0].user) setHome(true) The issue here is that ...

acquiring JSON information from different domains

I am in need of creating an ajax request to fetch JSON data from a RESTful Web Service that is hosted on a different domain (KARAF using cxf). The client making the ajax call is situated on a separate domain (Apache Tomcat). The Web Service responds with ...

AccessMediaStream - camera direction

My current setup involves using an Android tablet and GetUserMedia to capture images in my program. It seems that by default, GetUserMedia uses the front camera. How can I set the rear camera as the default instead? Below is the code snippet I am using w ...

`Is there a way to sort a deeply nested object by its values?`

I need assistance sorting an array of hospitals based on the lowest value of the amountinINR key, especially when dealing with deeply nested arrays of hospital objects. Does anyone know how to achieve this without using third-party libraries like lodash or ...

The callback function is not responding properly in my HTTP POST request

I'm currently working with some code that involves callbacks: function getUserToken(data, callback) { var password_sha256 = sha256(data.password); getAppById(data.app_id).then(function(res) { console.log("app"+res); if (!r ...

How come I'm facing difficulties when trying to send a post request to my WebApi using AngularJS's POST method?

I've uploaded "mytest.html" to the IIS server, and this project consists of WebApi and AngularJS. However, I am unable to make a correct request to my WebApi. I'm not sure why? 【HTML Code Snippets】 <!DOCTYPE html> <html> ...

Retrieve the data from an HTTP Request using AngularJS

I've been working on creating a JavaScript function that sends an HTTP Request to retrieve data, but I'm struggling with how to handle and use the result in another function. Here are the two functions I've tried (both intended to achieve t ...

Using local variables in NodeJS callbacks

Despite the abundance of information on SO, I have yet to find a suitable answer to my particular situation. The following code snippet is causing me issues: for(var i=0; i < shop.collections.length; i++){ if(!shop.collection[i].active){ var dat ...

Congratulations! Your product has been successfully added to Magento using Ajax

While using Firebug, I discovered that JSON generates a message within the success function. However, I am having trouble figuring out how to display it. As a workaround, I attempted to add the following code snippet: if(data.status == 'ERROR'){ ...

Verify the entered information in the input field and showcase it in the display box after pressing the ENTER key

I need to display selected values of a tree structure in a show box on the other side of the page using code. However, I also need to include HTML input boxes in some lines of the tree structure so that users can input data. The challenge is getting the in ...

The class 'ConsoleTVsChartsCharts' could not be located

Attempting to implement Laravel charts using the package consoletvs/charts:6.*, Utilizing service providers ConsoleTVs\Charts\ChartsServiceProvider::class, With an alias: 'Charts' => ConsoleTVs\Charts\Charts::class, ...

Issue with comparing equality to zero

function compare() { var value1 = parseInt(document.getElementById("box3").value); var value2 = parseInt(document.getElementById("box4").value); var display = document.getElementById("box5"); if (value1 === 0 || value2 === 0) { display.value = ...

"Troubleshooting: Fixing the 'Firebase Cloud Function admin reference is not a function'

I recently attempted to transform the .WriteOn cloud function in my Firebase app into a scheduled cloud function. The goal was to create a function that would run every 4 days to delete messages older than 2 days. While this worked well for the .WriteOn fu ...

Tips on obtaining the element that was used as the event selector

I am facing a challenge with a specific issue. Within a div containing various elements, I have implemented a mouseover event. The issue arises when trying to target this particular div in the mouseover function, as there are multiple automatically genera ...

Unable to input characters consecutively into the text field because it is being displayed as a distinct function within the component

When attempting to bind a text field using the approach below, I encounter an issue where entering characters in the text field causes the control/focus to shift out of the field after the first character is entered. I then have to click back into the text ...

Menu Options in Material UI Navbar

I am currently working on incorporating an icon in my navbar that, when clicked, will reveal a dropdown list of notifications. Although I have come across several code examples for dropdown menus, none of them have completely assisted me or provided specif ...