Adjusting the settimeout delay time during its execution

Is there a way to adjust the setTimeout delay time while it is already running? I tried using debounceTime() as an alternative, but I would like to modify the existing delay time instead of creating a new one.

In the code snippet provided, the delay is set to 10 seconds. However, I am looking for a solution where I can update the delay time dynamically when a mouse event is triggered while the setTimeout function is still running.

Your guidance on this matter would be greatly appreciated. Thank you!

Answer №1

To simplify the process, you can utilize a custom Timer class. Check out the following example of its implementation. Use the method Timer.start to initiate the timer. In case you need to modify any data and run it again, employ Timer.interrupt. This function calculates the difference and restarts the process, allowing for logic modifications.

class Timer {
  constructor(cb, ms = 2000) {
    this._ms = ms;
    this.ms = ms;
    this.cb = cb;
    this.timer = null;
    this.startedAt = null;
  }
  start() {
    this.startedAt = new Date().getTime();
    clearTimeout(this.timer);
    console.log("started");
    this.timer = setTimeout(() => {
      this.cb();
    }, this._ms);
  }
  intrupt() {
    const timeSpends = new Date().getTime() - this.startedAt;
    const timeLeft = this.ms - timeSpends;
    if (timeLeft > 0) {
      this._ms = timeLeft;
      this.start();
    }
  }
}
console.time("TIME");
let counter = 0;
const timer = new Timer(() => {
  console.timeEnd("TIME");
  console.log("counter: ", counter);
});

timer.start();
setTimeout(function cancel() {
  counter++;
  timer.intrupt();
}, 1000);

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

When saving a canvas as an image, it only results in a blank, transparent image

I have a situation where I am iterating through an array of image elements sourced from a local folder, attaching them to a canvas. However, when attempting to save the canvas as an image, it is not being saved correctly. The resulting image appears to mat ...

Ways to retrieve slider value when button is clicked?

I am currently working on a range-slider that has two ranges and I need to retrieve the slider value in my javascript code. Here is my approach so far: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.cs ...

attempting to pass a boolean type through props resulting in a type error

Hey, check out this component I created: import * as Styled from './styles'; export type HeadingProps = { children: React.ReactNode | string; colorDark: boolean; }; export const Heading = ({ children, colorDark }: HeadingProps) => { re ...

Lending a hand in deselecting a rule within the jcf-hidden add-on using Selenium

Currently, I am working on automating a website that utilizes the jcf-hidden class (a form of jQuery class) which hides the select element I want to access. By removing the display: block !important; property, I was able to successfully interact with the ...

Pull in class definitions from the index.js file within the node_modules directory

In my project, I have the package called "diagram-js" in the node_modules. The file node_modules/diagram-js/lib/model/index.js contains multiple class definitions as shown below: /** * @namespace djs.model */ /** * @memberOf djs.model */ /** * The b ...

Transitioning from Webpack to Vite: Resolving Path Alias and Ensuring Proper Imports

Recently, I decided to transition my project from Webpack to Vite with "vite": "^4.3.9",. However, upon running npm start, I encountered the following error: Error: The dependencies imported could not be resolved: In my React Typesc ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...

Is there a way to grab the inner content of an e-mail link by right-clicking on it?

I am currently developing a Chrome Extension that functions similarly to the "Search on Google" feature when you right-click on selected text. However, I am facing an issue with making it work when right-clicking on a mailto: email link. How can I extract ...

Issue with Angular.forEach loop malfunctioning

Here is the code for my custom filter that includes a parameter called viewbookoption, which is a dropdown value. Depending on the selected value from the dropdown, the data will be displayed in a grid. I have used a forEach loop in this filter, but it see ...

methods for obtaining access in JavaScript when dealing with an ArrayList<Object> that has been converted to a JSONArray

I am dealing with an Object ArrayList that contains various variables, stored in an ArrayList of Objects. I then convert it to a JSONArray and pass it to a JSP page. How can I display these objects in a textarea on the JSP page using JavaScript? public cl ...

React TypeScript - creating a component with a defined interface and extra properties

I'm completely new to Typescript and I am having trouble with rendering a component and passing in an onClick function. How can I properly pass in an onClick function to the CarItem? It seems like it's treating onMenuClick as a property of ICar, ...

Tips for formatting a Date field within an Angular application

After receiving a stringVariable from the backend service, I successfully converted it into a Date field with the following code snippet. date d = new Date(stringVariable ); While this conversion worked fine, the resulting date format is not what I requ ...

Chrome fails to read font family correctly

I created a jsfiddle that demonstrates an interesting behavior with setting and reading the font-family using jQuery. When I set the font-family to "Arial . . ." it reads back okay, enclosed in a single set of double quotes. However, when I set the font-fa ...

Tips for retrieving next-auth authOptions from an asynchronous function

I need to retrieve values from AWS Secrets Manager and integrate them into the authOptions configuration for next-auth. The code implementation I have is as follows: export const buildAuthOptions = async () => { const secrets: AuthSecrets = await getS ...

Unveil Secret Divs with a Click

I am in search of a way to display a hidden div when I click on a specific div, similar to the expanding images feature in Google's image search results. I have made progress with my limited knowledge of javascript, as shown in this CodePen: http://co ...

Is it possible to design a Typescript type that only contains one property from a defined set and is indexable by that set as well?

I have the different types listed below: type OrBranch = { or: Branch[] } type AndBranch = { and: Branch[] } I need a type called Branch that can either be an OrBranch or an AndBranch. I initially attempted this: type Branch = AndBrand | OrBranch ...

Setting up a custom PrimeNG theme to match our unique style is a great way to

I am currently using the most recent version of "primeng": "^12.2.0", and I am looking to implement my own custom theme for primeng. Despite searching through numerous blogs, I have yet to find a solution. In an attempt to create my cu ...

Tips for transferring data from a service to a method within a component

I have a service that successfully shares data between 2 components. However, I now need to trigger a method in component A when an event occurs on the service (and pass a value to that component). Can someone guide me on how to achieve this? I have seen ...

I am unable to send back my JSON object

I seem to be having trouble returning a JSON object as all I get is an undefined variable. The code below is supposed to fetch a JSON element from an API. It appears to work within the success: function, but when attempting to use that data elsewhere, it ...

PHP array utilized in a dynamic dropdown menu

I am working on creating a PHP array for a select list that has dynamic options populated using JavaScript. My goal is to collect all the options selected and display them on the next page. I was wondering if there is a better way to achieve this task. C ...