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

Guide to sending jQuery data back to main class in TypeScript

Hi everyone, I'm diving into the world of typescript and JQuery. I have a simple question. In my typescript class called DatePicker, I am calling a function. Here's a snippet of the code: Class DatePicker { private pickerData; public update( ...

What is the best way to recover past messages from a channel?

I am working on a bot that is supposed to be able to retrieve all messages from a specific server and channel upon request. I attempted to use the channel.messages.cache.array() method, but it only returned an empty array []. How can I efficiently fetch ...

Is there a better option than the Korean Syllable PHP or JavaScript Romanizer?

I am currently working on creating a transliterator from the Korean alphabet (hangul) to the Latin alphabet (romanization). However, after several unsuccessful attempts using a simple associative array, I have realized that it may not be the most effective ...

"Unlocking the Power of Material UI withStyles() in React JS: Mixing and Matching Styles for Stunning

I am working with the following code snippets: const styles = theme => ({root: {backgroundColor: '#000000'}) const styles2 = theme => ({root: {backgroundColor: '#fff'}) In my React component, I am using export default compose( ...

What are the steps to execute PhantomJS on a client machine?

I have implemented an HTML to PDF converter that utilizes phantomjs, following this method: npm install -g html-pdf var fs = require('fs'); var pdf = require('html-pdf'); var html = fs.readFileSync('./test/businesscard.html' ...

Having trouble setting up a new Angular project using NodeJS?

I am encountering an issue while attempting to create a project following the installation of angular-cli on my system. Upon running the command ng new project-name, I am faced with the following error message: ERROR: 21328 verbose stack Error: EPERM: ...

How can we show a div element when hovering over another element using css-in-js?

Is there a way to use material ui withStyles component in order to show information only on hover for a specific div? ...

Understanding the behavior of subjects and observables in Angular 8 is crucial for

I have made a REST service data call that is executed 3 times. In order to reduce the number of calls to just once, I need to create a data service that stores a local copy of the data. If the copy has not been populated yet, it will fetch the data from th ...

Retrieving information from Flask server using an Ajax request

Exploring Flask and Ajax, my server-side web application is meant to double and return a passed number. I adapted the code from the example on Flask's site, resulting in this Python snippet: from flask import Flask, request, jsonify # Initialize the ...

Unlocking the invitable_friends permission dialog on Facebook API: A step-by-step guide

During the installation process of an app, users are given the choice to revoke the invitable_friends permission. If this happens, I would like to request the invitable_friends permission again. Some apps seem to be able to open a dialog requesting this pe ...

How to handle event methods with Vue

Currently, I am facing a challenge in passing an event downward with a bound change listener to a child input component. Although I am utilizing wrapped input components, my goal is to define methods within the parent component. //App.js: <currency-inp ...

Is there a way to append a unique property with varying values to an array of objects in TypeScript?

For instance: items: object[] = [ {name: 'Backpack', weight: 2.5}, {name: 'Flashlight', weight: 0.8}, {name: 'Map', weight: 0.3} ]; I prefer the items to have an 'age' property as well: it ...

The input value fails to update after the method is called

I am working on developing a todo-list application and here is the code I have so far: HTML: <div class="divPadder"> <input ref="makePlaceholderEmpty" class="inputBoxSize" type="text" :placeholder="placeholder"v-model="task"> <ul> ...

The server encountered an issue with starting the ANCM Out-Of-Process, resulting in HTTP Error 502

We currently have two projects in progress. One involves a Web API built on .NET Core 2.2.6 and an Angular 8 Single Page Application integrated within .NET Core 2.2.6. Both projects have been deployed on IIS 7 with the Web API functioning properly, but the ...

Explore the titles provided by Wikipedia

Hi there, I'm fairly new to Angular and trying to work with the Wikipedia API. However, I seem to be having trouble getting 4 titles from the API. Here's an example URL for one of the titles: https://en.wikipedia.org/w/api.php?action=query&pr ...

Prevent resizing or zooming on AmCharts4 radar chart

Is there a way to disable the click-drag zooming feature on the AmCharts4 radar chart in my react application? Thank you. View image of the chart ...

What is the best way to modify an array within separate functions in a NodeJS environment?

I am facing an issue where I want to update an object inside the fetchAll() functions and then send it back after successful updation. However, the response I receive is '[]'. var ans = [] Country.fetchAll(newdate,(err, data) => { if ...

Angular 2 click event with changing function name

Even though this question seems simplistic, I'm having trouble figuring it out. As someone new to Angular 2, I've tried various combinations of {}, [], and () brackets to make the following work: <button (click)="this.action">Click me</ ...

Develop a child interface within Typescript

I am unsure if the term sub interface is correct, but my goal is to develop an interface that inherits all properties from the super interface except for some optional ones. Despite referring to the TypeScript documentation for interfaces, I was unable to ...

It is not possible to upload files larger than 4mb in ASP.NET MVC3

I am facing an issue with uploading files in ASP.NET MVC3 where I am unable to upload files larger than 4mb. I am currently using jquery.form.js for the file upload process and utilizing ajax to post the form to the server side. It works perfectly fine whe ...