Mouse event listener includes timeout function that updates a global variable

I'm currently working on a function that gets activated by a mouse click, but there's a 10-second cooldown period using setTimeout() before it can be triggered again. However, after the timeout, my variable doesn't get set to the correct boolean value.

//Function called on every mouse click
@HostListener("document:click", ["$event"])
public documentClick() {
console.log("1: " + this.active);

  //Only execute if active is true
  if (this.active === true) {

    //Setting active to false to prevent re-entry
    this.active = false;
    console.log("2: " + this.active); 

    //Wait for 10 seconds before setting active back to true
    setTimeout(() => {
      this.active = true;
      console.log("3: " + this.active);
      //Prints 'true' after 10 seconds
    }, 10000);

  }

}

After the timeout, the variable this.active is correctly set to true. But when I click again following the timeout, the console prints "1: false" instead of expecting "true".

Answer №1

this keyword in a JavaScript function pertains to the scope of that particular function. To access member variables, you can utilize arrow functions instead. Give this a try:

setTimeout(() => {  // <-- using an arrow function here
  this.active = true;
  console.log("3: " + this.active);
  // This will print as true after 10 seconds
}, 10000);

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

Angularjs and Angular (5) routing combo

I'm currently exploring the possibility of running angular alongside our existing angularjs application. Instead of immediately diving into the tedious process of transitioning to ngUpgrade, I wanted to attempt running them independently first. My ide ...

The issue with session storage persisting even after closing the iframe

Encountering a persistent issue where the sessionStorage remains populated even after closing an iframe and opening another one with the same destination. I assumed that the sessionStorage would be reset and start afresh each time. The iframe is contained ...

Encountering issues with retrieving application setting variables from Azure App Service in a ReactJS TypeScript application resulting in '

My dilemma lies in my app setup which involves a Node.js runtime stack serving a ReactJs Typescript application. I have set some API URLs in the application settings, and attempted to access them in ReactJs components using process.env.REACT_APP_URL, only ...

Can you explain the process of the assignment part in the code line of Angular2?

I’ve been delving into the angular2-rxjs-chat project on GitHub to enhance my knowledge. Within the code linked here, there is a specific line of code that caught my attention: threads[message.thread.id] = threads[message.thread.id] || message.thread; ...

Angular Elements generates compact, single-line HTML output

It's incredibly frustrating how browsers handle inline-block elements, creating invisible margins when placed side by side. You can experience this "bug" firsthand here: http://jsfiddle.net/8o50engu/ Interestingly, if these elements are on the same l ...

Trouble with V-if not updating after property is modified within an async TypeScript function

There is a scenario where one HTML element becomes hidden after an async call returns from the server, while another HTML element is displayed: <template> <div v-if="!showElementTwo">Element 1</div> <div v-if="show ...

Learn the best practices for sharing .env values from the main project component to various reusable npm installed components

In recent projects I've worked on using React and Vue.js, I have utilized .env variables to store API URLs for micro services and other configuration settings that are used throughout the root project. However, when it comes to child components insta ...

Set up a unique database in memory for every individual test

Is it feasible to create an in-memory database for each test scenario? My current approach involves using the code snippet below, which functions properly when running one test file or utilizing the --run-in-band option. import _useDb from "@/useDb&q ...

Tips for concealing the top button on a mat calendar

I have a calendar for a month and year, but when I click on the top button it also displays the day. How can I hide that button or instruct the calendar not to show the days? Check out this image I was thinking of using a CSS class to hide that element. ...

React Material-UI is notorious for its sluggish performance

I recently started using React Material-ui for the first time. Whenever I run yarn start in my react app, it takes quite a while (approximately 25 seconds) on my setup with an i5 8400 + 16 GB RAM. Initially, I suspected that the delay might be caused by e ...

Comparing TypeScript and C++ in terms of defining class reference member variables

class B; class A { A(B b_) : b{b_} {} B &b; }; In C++, it is possible to have a reference member variable like 'b' in class A. Can the same be achieved in TypeScript? Alternatively, is there a specific method to accomplish this in ...

Displaying icons representing different countries using Angular framework

Seeking assistance with Angular - I obtained a collection of country icons (svg format) from flat icon and intend to display them based on the respective countries in my project. With 870 icons, what would be the simplest approach to accomplish this with ...

Blueprint for constructing an optimal Angular and Spring Boot application.Creating a streamlined process for

I am currently working on constructing a spring boot/angular application. My goal is to run it locally in order to work on the front end login/logout process. To do this, I have angular set up to run on port 4200 and spring boot running on port 8080. How ...

The error message "The element 'router-outlet' is unrecognized during the execution of ng build --prod" appears

I encountered a specific error message when running ng build --prod, although the regular ng build command works without issue. Error: src/app/app.component.html:1:1 - error NG8001: 'router-outlet' is not recognized as an element: 1. If 'rou ...

Error in React Typescript: No suitable index signature with parameter type 'string' was located on the specified type

I have encountered an issue while trying to dynamically add and remove form fields, particularly in assigning a value for an object property. The error message I received is as follows: Element implicitly has an 'any' type because expression o ...

Tips for obtaining the OneSignal playerID

When launching the app, I need to store the playerID once the user accepts notifications. This functionality is located within the initializeApp function in the app.component.ts file. While I am able to retrieve the playerID (verified through console.log) ...

Transform Text into Numeric Value/Date or Null if Text is Invalid

Consider the TypeScript interface below: export interface Model { numberValue: number; dateValue: Date; } I have initialized instances of this interface by setting the properties to empty strings: let model1: Model = { numberValue: +'', ...

Issue with upgrading node from 12v to 16v: Trying to access a property that does not exist, specifically 'splice', within a circular dependency in module exports

After upgrading the node version from 12 to 16, we encountered a debugging console error. The 'Promises' are failing to resolve following this error, leading to the termination of further execution. (node:28112) Warning: Accessing non-existent p ...

Typescript: The type 'Observable<{}>' cannot be assigned to the type 'Observable'

I'm encountering an issue with the Observable type, any thoughts on how to resolve it? import { PostModel } from '../model/postModel'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable&ap ...

Tips for coding in Material-UI version 5: Utilizing the color prop in the Chip component by specifying

Is there a better way to type the MUI Chip prop color when the actual value comes from an object? Using any doesn't seem like a good option. Additionally, is keyof typeof CHIP_COLORS the correct approach for typing? import { Chip, Stack } from "@ ...