The returned value of setInterval may be undefined or the scope could be incorrect

I attempted to save the current timestamp using Date.now() after invoking a callback with setInterval. Following that, I aimed to stop the interval from firing repeatedly by clearing it, all within a class structure. However, the variable where I stored the interval ID and expected it to be accessible "class-wide" remains undefined. I am certain that there is some issue with JavaScript scope, but I am unable to pinpoint it.

class Signal {
    t : number;
    private intervallId : number | undefined;
    
    
    constructor(t : number) {
        this.t = t;
              
    }

    wait() {
        
        this.intervallId = setInterval(this.signalTriggered, this.t)
        console.log("Never executed.")
    }

    signalTriggered() {
        const triggerTime : number = Date.now()
        console.log(this.intervallId) /* always undefined */
        if (this.intervallId) {clearInterval(this.intervallId)
        console.log(triggerTime); }
    }
}

var timer = new Signal(2000)
    timer.wait()
    console.log("Done.") /* Never printed out. */

Answer №1

The issue lies in the reference to this. The original reference is lost when you pass the method as an argument to the setInterval function.
One solution is to use an arrow function to encapsulate the method:

setInterval(() => this.signalTriggered(), this.t)

Alternatively, you can utilize Function.prototype.bind to preserve the reference to this:

setInterval(this.signalTriggered.bind(this), this.t)

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

Decoding AngularJS controller syntax

As a newcomer to angular js, I encountered a peculiar issue. I couldn't get the following code snippet to run: hello.html <html ng-app> <head> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">< ...

"Utilize JavaScript to detect both the loading and unloading events on a webpage

I attempted to capture the window.open onload and onunload events. The issue arises when I use URLs from other domains. For example: When the URL is for the same page, both events trigger as desired. window.open("/") View PLUNKER with same page URL .. ...

Using duplicate HTML elements with jQuery can cause the script to malfunction and become ineffective

Hello everyone! I am fairly new to jQuery and recently created a script that works perfectly for the HTML below. However, I am running into an issue when duplicating the HTML and script - after clicking, only the last project-info and project-images are be ...

Which is better for creating a partial panoramic view: iPhone panorama, three.js, or Pannellum

I have been facing this issue for the past 2 weeks, trying various JavaScript libraries like ThreeJS, but without any luck. Pannellum seems promising to me, especially in its support for partial panoramas with just one photo. My goal is to create a panor ...

The error message "Property navigate is undefined" appears when trying to open a full-screen modal in React Native navigation

Having an issue with rendering a full-screen modal in React Native when clicking the 'Account' button in the header. I keep getting this error: Cannot read property navigate of undefined Can anyone point out where my mistake might be? Here is ...

Troubleshooting a display issue with Chrome's User Agent - Possible CSS solution?

After recently installing a WordPress theme, I am encountering an issue with a Facebook conversion box not displaying when accessing my site through Chrome. Interestingly, this problem does not occur when using Firefox. Upon inspecting the element in Chro ...

Access JSON elements in real-time

Here is a JSON variable defined: var json = { input: "hello", payload: { pay1: 123, pay2: 456 } }; Next, let's define a variable called keypay1. var keypay1 = "payload.pay1"; Query 1: What method should be used to retrieve the value of json.payloa ...

Ways to achieve 8 columns in a single row using Javascript and Bootstrap

Recently, I created a simple function for searching movies and manipulating them in the DOM. The issue arises when a movie name is entered and the API response returns around 20-30 recommendations. I wanted to display this fetched data in 8 columns per row ...

Extracting multiple values using the .find method in JQUERY / JavaScript

I'm facing an issue with my JSP page form. When I submit the form, it generates a JSON string which is sent via AJAX post. The problem arises when I try to extract multiple values from the form using the following method: .find('input[name=ite ...

Adding a variety of data types to a MongoDB collection through Node.js

I'm currently using the Sails web framework along with Node.js and MongoDB to develop my own website. I am encountering some challenges while attempting to add a new user and input values (of different types: Number, Array, Object) to my 'users&a ...

The page keeps scrolling to the top on its own, without any input from me

Whenever I reach the bottom of the page, my function loads new items seamlessly. However, an issue arises when the new items load, causing the scrolling position to abruptly return to the top of the page. This disrupts the user experience and is not the de ...

The share-modal.js file is throwing an error because it is unable to read properties of null, particularly the 'addEventListener' property, at

I encountered an error that I want to resolve, but it's proving to be quite challenging. Despite extensive searching on Google, I haven't found a solution yet. Uncaught TypeError: Cannot read properties of null (reading 'addEventListener&apo ...

Error: The function window.intlTelInput is not recognized within the ReactJS framework

I am currently learning ReactJS and encountering an issue when using jQuery with React JS for intlTelInput. I have installed npm jQuery and imported all the necessary code. Additionally, I have included all the required CSS and jQuery links in my index.htm ...

Mastering advanced String templating using loops and control statements in Javascript

During runtime, I receive an array similar to the example below: var colors = ['red', 'green', 'blue']; I then need to create a JSON String that looks like this: { "color" : { "name" : "foo", "properties ...

Alter based on the RegEx JS value

I have a regular expression that looks like this: /\\.br<[0-9]+>\\/g. I am looking to replace it within the main text with the number of new lines specified between the <> in the regular expression. For example, input: Hel ...

Check the browser's developer tools to access JavaScript files

I recently came across a server at example.noodles.com that is hosting a node.js application. I'm curious if there's a way to access the source files of this application using inspect element or some other method? Up to now, all I've been a ...

Ajax does not pass any data to PHP script

I am facing an issue while trying to send a variable from JavaScript and then use it in my PHP code. I have created a function for this purpose but when I execute it, the functionality doesn't work as expected. Can someone help me troubleshoot this pr ...

The storage format of the input field is handled differently on the angularjs controller side

Check out the plunker link for this directive in action. A comma is automatically added as the user types in the input, and it displays numbers with 2 decimal places. However, there seems to be an issue where entering '2300.34' results in ' ...

Connecting different jQuery methods to create a chain

From my understanding of jQuery chaining, the first method in the list must complete before the next method executes. Here is an example: $.fn.reportZebraStriper = function(options) { console.log('reportZebraStriper()'); return true; } ...

Utilizing Node.js and Express to create router instances integrated with a database functionality

My understanding from researching the Express documentation is that when declaring an express.Router(), it creates a single instance of a router where you can assign a routing path and execute logic. The concept of a router being like a mini-app for specif ...