Is there a way in JS to wipe out all methods, classes, setTimouts, and setIntervals in one swift action?

I am working on creating an animation with a class that involves calling other classes, methods of other classes, setTimeouts, and more. My current task is to implement an exit button for this animation. When this button is clicked, I need all the classes, methods, loops, etc. to stop functioning. What would be the most effective approach to achieve this?

// Here is the code for building the HTML for the animation
class BuildPhone{
  constructor(idElement) {
    this.create(idElement)
  }
  create(idElement) {
    this.createWrap(idElement)
    this.createDisplay()
    this.createElements()
  }
  createWrap(idElement){
    document.querySelector('idElement')
    // Set up wrapper for the phone
  }
  createDisplay(){
    // Set up display for iPhone
  }
  createElements(){
    // Define elements like time display, Wi-Fi, battery level, and buttons (Home, Back, Apps)
  }
}

// Class for running the chatting animation
class Chat{
  constructor(messages){
    this.messages = messages
    this.startChating()
  }
  async startChating(){
    const timeout = (ms) => new Promise(resolve => setTimeout(resolve, ms));
    
    var timerFunc = function(i) {
      return async function() {
        await timeout(3000); // Introduce a 3-second delay before sending a new message

        this.sendMessage(this.messages[i])
        this.scrollToBottom()

        if (i < this.messages.length) {
          setTimeout(timerFunc(++i), 0); 
        }
      }
    }
    setTimeout(timerFunc(0), 500); // Start the loop
  }
  sendMessage(message){
    // Add the message text to the list of chat messages
  }
  scrollToBottom(){
    // Code for scrolling to the bottom of the chat after sending a message
  }
}

class PhoneAnimation{
  constructor(args) {
    create(args)
  }
  async create(args) {
    // build HTML for animation
    await new BuildPhone(args.idElement)
    // run chatting animation
    await new Chat(args.messages)
  }

}

// ------ Initialization -------
args = {
  idElement: '#targetElement1',
  messages: [
    {
      from: 'app',
      text: 'hello)'
    },
    {
      from: 'user',
      text: 'hi'
    },
    {
      from: 'app',
      text: 'how are you?'
    },
  ]
}

// Initialize the animation
new PhoneAnimation(args)
//HOW TO KILL ALL ANIMATION IF IT IS RUNNING?

The desired result is to stop all classes, async methods, functions, setTimeouts, and setIntervals using a specific mechanism.

Answer №1

In JavaScript, the setTimeout function can provide a handler that allows you to terminate the timer.

var timer;

function tick() {
   // some actions here
   timer = setTimeout(tick, 1000);
}

function stop () {
  if (timer) {
    clearTimeout(timer);
    timer = undefined;
  }
}

Note: The following code is just a basic example and does not include the capability to restart, but it can be easily enhanced.

var timerHub = {
   "timers":{}
  ,"setTimeout": function (groupName, fn, time) {
                   groupName = groupName || "@";
                   var timer = setTimeout(fn ,time);
                   if (! timers.hasOwnProperty(groupName)) { 
                     timers[groupName] = {"isStopped":false,"list":[]};
                   }
                   timers[groupName].list.push(timer);
                 }
  ,"isStopped": function (groupName) {
                   groupName = groupName || "@";
                   if (! timers.hasOwnProperty(groupName)) { 
                     return true;
                   }
                   return timers[groupName].isStopped; 
                 }
  ,"stop": function (groupName) {
                   groupName = groupName || "@";
                   if (! timers.hasOwnProperty(groupName)) { 
                     return;
                   }
                   timers[groupName].isStopped = true; 
                   timers[groupName].list.map((t) => {
                     if (!t) return t;
                     clearTimeout(t);
                     return undefined;
                   });
                 }
};

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 exporting several Chart.JS graphs to a PDF document with each graph on a separate page

I am currently utilizing the JavaScript code provided below to generate a pdf file containing multiple charts. However, all the charts are being placed on a single page. My inquiry is regarding how I can customize the code to have each chart on its own sep ...

Sanitize input data prior to using express-validator in a Node.js application

In my Node.js project, I am utilizing the V4 syntax of express-validator as recommended: const { check, validationResult } = require('express-validator/check'); const { matchedData } = require('express-validator/filter'); Additionally ...

Buttons failing to adjust the color of the background and text

There seems to be an issue with this piece of code. I can't quite put my finger on it, but something is definitely off. I am trying to make it so that when a button is clicked, the background color and text font changes. Unfortunately, this is not wo ...

Troubleshooting the onExited callback issue with Popover component in Material UI

<Popover key={element.name} classes={{ paper: classes.paper }} open={open} anchorEl={this.myRef.current} anchorOrigin={{ vertical: ' ...

Observables do not provide any results when used in a pipe with an image src

I recently created a custom pipe for the image src in my application: It is applied to selectors like this: <img [src]="myobject?.URL | secure" /> Here's the code snippet for the pipe: import { Pipe, PipeTransform } from '@angular/c ...

What is preventing me from performing CPU profiling in Node.js when the process is blocked by the operation String(str).replace(some_regexp, '')?

As an illustration, the blow function testReplace will block the Node.js process: function testReplace() { let str = '<br/> 早餐后自由活动,于指定时间集合自行办理退 ...

How to rotate text direction using JavaScript and CSS

Despite my extensive efforts, I have been unable to find a solution to a seemingly simple problem. In JavaScript, I have generated dynamic text using the following code: context.fillText('name', 10, 10, 20); Now, I need this text to be ori ...

Ways to fix the error of "Uncaught TypeError: Cannot convert undefined or null to object"

Here is a function that I am working on: function collect_que_ids(e) { var val = e.val(); var data_lo = e.attr('data-lo'); new_hash = {}; new_hash[val] = data_lo; if(e.is(':checked')){ if(checked_box_hash.includes(new_has ...

Is it possible for a jQuery selector to retain its object? What can be done to prevent it

One interesting scenario involves a dropdown element within a container. <div class='container' /> <script> var dropdown = "<select class='multi-dropdown'> ... </select>" </script> Every time the value ...

Is being unfazed by work a common occurrence?

After completing a complex cycle that processes data from the database and writes it to an array, I encounter a situation where the array processing function is triggered before the array is fully populated. This forces me to use setTimeout() for proper ti ...

Guide on parsing an Array of arrays using JSON.parse

I have received a JSON.stringified Array of arrays in a variable named request. alert(request); When I alert the above, I get the following message: "[[\"0\",\"MahaShivRatri\"],[\"0\",\ ...

Tips for changing the page URL upon click in a Vue.js application

I am currently developing a post board application using Vue.js and I am facing an issue with redirecting the page when a user clicks on each post. To handle this, I have made use of vue-route and axios in my project. Here is a snippet from index.js, ex ...

What steps can be taken to stop the update function from inserting data into MongoDB from a Meteor application

Within my Meteor method, I have implemented a function to check for existing documents. If the document is not found, it gets inserted into the database. However, if it is found during a second attempt, the document is updated and a new one is also inserte ...

What can be done to prevent unnecessary API calls during re-rendering in a React application?

On my homepage, I have implemented code like this: {selectedTab===0 && <XList allItemList={some_list/>} {selectedTab===1 && <YList allItemList={some_list2/>} Within XList, the structure is as follows: {props.allItemList.map(ite ...

Ajax is invoked only one time

The system is set up to display a follow button and an unfollow button. Clicking the follow button should make the unfollow button appear, and vice versa. Currently, when you click "follow", the database updates and the follow button disappears while the ...

What is the process for implementing Autocomplete in JsHelper?

Is it possible to create an Ajax Autocomplete using only pure JsHelper in JavaScript? Thank you, Celso ...

Unraveling the mystery of "??=" in Javascript/Typescript code

In a recent TypeScript code snippet, I came across the following: const arrayAA: Record< someSchema['propX'], typeof arrayBB > = {}; for (const varB of arrayBB) { (arrayAA[someStringValue] ??= []).push(varB) } What is ...

ProgressMeterJS Plugin - Full-width Progress Bar

I have encountered a question regarding this particular plugin found at: My goal is to adjust the progress bar's width to 100% so it matches the width of its container. So far, I have made modifications to the plugin by changing the following line: ...

Securing API data: Utilizing encryption techniques in express and nuxtjs to deter scraping efforts

I'm looking for a secure way to encrypt my API data in order to prevent users from viewing it in the network tab or as plain text within objects like window.__nuxt__. Currently, I am following these steps: Encrypting data on the back-end using a sec ...

What is the process for integrating php script within javascript?

Is it possible to incorporate php scripts into javascript[1] in the same manner as it can be done in html[2]? server.php: <?php echo 'hello World'; ?> client.js (or client.php if needed): function foo() { var i = <?php include ...