0
votes

In typescript, I am trying to reset a timer based on a click function. I have looked at the solutions around clearTimeout, but they don't seem to fit the situation where I have the setTimeout() defined in a class.

import { ModalAction } from "./modalScript.js";
export class Timer {
  private interval: number;
  constructor(interval: number) {
    this.interval = interval;
  }

  startTimer() {
    console.log("startedTimer");
    setTimeout(function () {
      let mod = new ModalAction();
      mod.renderModal();
    }, this.interval);
  }
  resetTimer() {
    clearTimeout();
  }
}

In my external class, I am creating a new Timer class passing in an interval. I would like to be able to call myTimerObject.clearTimeout() from my external class. clearTimeout expects a number. i have tried setting startTimeout() to a variable, but when calling it in clearTimout(), it does not read as a number.


Implemented the suggestion and it works, with a couple of changes and a new question. I had to declare the variable in the constructor, otherwise typescript complained of not initialized. So now, when I create the new object from my external class, I have to pass in a number argument. I randomly pass in the number 1. seems a little unclean, but it functions. Any improvements??

import { ModalAction } from "./modalScript.js";
export class Timer {
  private interval: number;
  **private handler: number;**
  constructor(interval: number, **handler: number**) {
    this.interval = interval;
    **this.handler = handler;**
  }

  startTimer() {
    console.log("starting timer");
    this.handler = setTimeout(function () {
      let mod = new ModalAction();
      mod.renderModal();
    }, this.interval);
  }
  resetTimer() {
    console.log("timer reset");
    clearTimeout(this.handler);
    this.startTimer();
  }
}

Is built with myObject = new Timer(10000, 1);

1
Can you clarify what you're trying to accomplish? Do you want to effectively cancel the timeout before the interval is reached and the callback is performed? - Luke
Does this answer your question? How to cancel setTimeout from this? - Heretic Monkey

1 Answers

1
votes

You can fix your code by assigning the setTimeout result to a variable and use it in clearTimeout.

import { ModalAction } from "./modalScript.js";
export class Timer {
  private interval: number;
  private handler?: ReturnType<typeof setTimeout>;
  constructor(interval: number) {
    this.interval = interval;
  }

  startTimer() {
    console.log("startedTimer");
    this.handler = setTimeout(function () {
      let mod = new ModalAction();
      mod.renderModal();
    }, this.interval);
  }

  resetTimer() {
    clearTimeout(this.handler);
  }
}

alternatively you can use number as the return type of setTimeout.