Troubleshooting issues with setTimeout in Angular 2 using typescript

Within this HTML code, I am monitoring the page for idle activity. If the user is idle for a certain period of time, an inactivity alert will be displayed and the user will be logged out.

<div *ngIf="environmentData" xmlns="http://java.sun.com/jsf/html" (load)="startTimers()" (mousemove)="resetTimers()" (keypress)="resetTimers()">

In the TypeScript component where these functions are defined, I have set the timeout duration to 10 minutes. However, the alert appears every time there is mouse movement or a key press. Why isn't it waiting for the specified time before showing the alert?

// Start timers.
  startTimers() {
    console.log("inside start timers method");
    console.log("timeout number is " + this.timeoutNow);
    this.timeoutTimer = setTimeout(this.showTimeout(), this.timeoutNow);
    // window.location.href = this.environmentData.logoutUrl;
  }

  showTimeout(){
    console.log("inside show timeout");
    bootbox.alert("You are being timed out due to inactivity!");
  }

  // Reset timers.
  resetTimers() {
    console.log("inside reset timers method");
    clearTimeout(this.timeoutTimer);
    this.startTimers();
  }

Answer №1

One correct way to do it is:

this.timeoutTimer = setTimeout(this.showTimeout, <arg2>);  // the right way

Rather than:

this.timeoutTimer = setTimeout(this.showTimeout(), <arg2>);  // this is incorrect

The reason being, in the latter approach, you're immediately executing the callback function instead of passing its reference.

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

Guide to seamlessly incorporate a HTML template into your Angular 7 project

I'm currently in the process of integrating an HTML template into my Angular 7 project, and unfortunately, it does not seem to be functioning as expected. To start off, I have placed the template files under assets/template/.. and included the necess ...

Ionic2: expanding menu options in the sidemenu

I'm not very familiar with ionic, but I have a question on behalf of my friend who is hesitant to ask on StackOverflow because she's unsure of how to frame her question. She simply wants to learn how to implement a submenu in an ionic 2 side men ...

Developing a user interface that filters out a specific key while allowing all other variable keys to be of the identical type

As I dive deeper into the TypeScript type system, I find myself grappling with an interface design query. Can anyone lend a hand? My goal is to craft an interface in TypeScript where certain object keys are of a generic type and all other keys should be o ...

SonarLint versus SonarTS: A Comparison of Code Quality Tools

I'm feeling pretty lost when it comes to understanding the difference between SonarLint and SonarTS. I've been using SonarLint in Visual Studio, but now my client wants me to switch to the SonarTS plugin. SonarLint is for analyzing overall pr ...

Tips on transforming data stored in an array into a nested array structure using Angular 13

Just starting out with Angular and I'm looking to convert my data into a nested array format in Angular 13. If anyone has a StackBlitz example, that would be greatly appreciated! This is the data I've retrieved from a random API: "data& ...

Generate the test output and save it to the distribution folder

When setting up my Angular 9 application in a Jenkins pipeline, I include two key steps: npm run test:prod, which translates to node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng test --prod; and npm run build:prod, translating to node --ma ...

Personalized hue for angular2-material's md-progress-circle component

Is it possible to customize the color of my md-progress-circle element to something other than the default? <md-progress-circle mode="determinate"></md-progress-circle> I'm facing an issue where I cannot find a specific class to over ...

The compatibility issue arises when trying to utilize Axios for API calls in Ionic 6 React with react-query on a real Android device in production. While it works seamlessly on the emulator and browser

My form utilizes react-hook-form to submit data to a server. Here is the code: <FormProvider {...methods}> <form onSubmit={handleSubmit(onIndividualSignup)}> <Swiper onSwiper={(swiper) => setSlidesRef(s ...

Guide to making a ng-bootstrap modal that retains a component's state

I am currently working on implementing a modal with Angular by following a tutorial on the ng-bootstrap website ( - in the "Components as content" section). However, I am facing a challenge where I want the component displayed in the modal to retain its st ...

I am having trouble figuring out the issue with the state and how to properly implement it in Typescript

I am having difficulties sending emails using Nodemailer, TypeScript, and NextJS. The contact.tsx file within the state component is causing errors when using setform. As a beginner in TypeScript, I have been unable to find a solution to this issue. Any he ...

What is the best way to extract a value from an input tag within a TSX component and then utilize that value in a Node JS file located in a separate directory?

Currently, I'm immersed in a personal project where I'm utilizing Fetch to pull data from an API. The challenge I'm facing involves sending a call from my index.js file to a TSX component when a SearchButton component is clicked. However, th ...

What could be causing my redirection to not load the correct component as expected?

I'm encountering an issue with my Angular application where a redirect in the routing module is not hitting the expected routes and instead falls through to the wildcard route. Here's a simplified example of the problem: const routes: Routes = [ ...

Disregarding TypeScript import errors within a monorepo ecosystem

In my Turborepo monorepo, I have a Next.js app package that imports various components from a shared package. This shared package is not compiled; it simply contains components imported directly by apps in the monorepo. The issue arises with the shared co ...

Using Material-UI with TypeScript

Attempting to integrate TypeScript/React with Material UI has been quite the challenge for me so far. Here is my index.tsx file: declare function require(p: string): any; var injectTapEventPlugin = require("react-tap-event-plugin"); injectTapEventPlugin( ...

How can I dynamically insert various FormGroup instances into a FormArray in Angular?

I am looking to dynamically populate the order array with multiple dishes. Each dish will be stored as a FormGroup in the form, such as pizza, salad, drink, or any other type of dish. Prior to adding any items, the form structure should resemble this: this ...

Error message: The function ctorParameters.map is not defined

I am currently experimenting with implementing dragula in my angular2 application. Here is the snippet from my code containing the app.module: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@ang ...

Insert a gap between the File Input button and the Placeholder text

https://i.sstatic.net/Gnm6u.png I'm currently attempting to create a separation between the "Choose File" button and the "No file chosen" area, similar to what is shown in the image above. Below is the HTML code I am using: <p class="mb-0 f- ...

What is the most effective method for achieving a desired outcome?

Is it a valid approach to get an action result, and if so, how can this be achieved? For instance, if there is a page with a form for creating entities, after successfully creating an entity, the user should be redirected to the entity's detail view. ...

Creating a dynamic form in Angular using reactive forms and form builder that pulls real-time data from the server

I have been struggling for the past two days to organize the data in the correct order but so far, I haven't been successful. Essentially, I retrieve some data from the server and present it to the client along with additional fields that the client n ...

Tips for displaying a single item in Angular2 and Ionic2

I am new to Angular and seeking help as I am facing an issue with my NodeJS server running socket.io. Despite trying to find a solution online, I have been unsuccessful so far. Here is my server code: SERVER var socket = require('socket.io'), ...