JavaScript Class Emit Signal for establishing a sequence of interconnected events

My Vue project includes a JavaScript class specifically for mobile devices. I'm looking to have this class emit a signal once the property 'hasEnded' is set to True for my object. How can I achieve this and chain together other events based on the completion of this class?

For example, when the user clicks 'Start' and the first timer counts to 100, I want the next one to begin. I aim for reusability and believe firing an event or signal would be ideal.

I don't possess extensive knowledge in mobile development, so if events aren't supported on mobile phones, what alternative should I consider?

class Counter {
  constructor(name) {
    this.hasEnded = false;
    this.value = 0;
    this.maxValue = 100;
    this.intervalID = null;
    this.elementName = ''
    this.elementName = name;
  }

  start() {
    this.intervalID = setInterval(this.increment.bind(this), 10);
  }

  increment() {
    this.value++

    var el = document.querySelector('.' + this.elementName);
    el.innerHTML = this.value;

    if (this.value == this.maxValue) {
      this.hasEnded = true
      clearInterval(this.intervalID);
    }
  }
}


window.addEventListener('load', function() {
  let counterA = new Counter('counterA');

  let counterB = new Counter('counterB');
  /*
        -- pseudo code --
      when counterA.hasFinished == true {
        counterB.start()
      }
  */

  var start = document.querySelector('.start');
  start.addEventListener('click', function() {
    counterA.start();
  });
})
<button class="start">Start</button>
<br>
<label>CounterA:</label>
<label class="counterA"></label>
<br>
<label>CounterB</label>
<label class="counterB"></label>

Answer №1

To create a signal, the most straightforward method is to trigger an event using the EventTarget.dispatchEvent() function. This function is accessible on objects like window, document, and all HTML elements since they are extensions of this class. By dispatching events, you can send signals that other components can capture.

In order to operate counters in sequence, you need a system that manages them as a list. The list begins at index 0 and continues until all items have been processed.

You can combine event dispatching with list structure to achieve this sequential behavior. Each time a specific event occurs, progress to the next item in the list.

A practical demonstration utilizing these concepts is shown below. A new class called CounterCollection has been created to handle the list. It listens for a custom event named counterend, which signifies the completion of a counter, and automatically moves to the next one until the list is exhausted. For illustrative purposes, a reset function is included to allow multiple executions.

class CounterCollection {
  // Implementation details
}

// Other classes and functions
<button class="start">Start</button>
<br>
<label>CounterA:</label>
<label class="counterA"></label>
<br>
<label>CounterB</label>
<label class="counterB"></label>

Events play a crucial role in JavaScript and web development. To verify browser support for specific technologies, APIs, or syntax, you can refer to caniuse.com for compatibility information.

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

Error message stating: "Form control with the name does not have a value accessor in Angular's reactive forms."

I have a specific input setup in the following way: <form [formGroup]="loginForm""> <ion-input [formControlName]="'email'"></ion-input> In my component, I've defined the form as: this.log ...

passing a variable from PHP to JavaScript

When I attempted to transfer variables from PHP to JavaScript, I found myself quite confused. It was straightforward for me to retrieve values using an ID, like this: var name = $("#name").val(); However, my question is if I want to convert a variable li ...

The tab key seems to be malfunctioning when triggered during a jquery change event

I encountered an unusual issue with my jQuery events, and I'm not entirely sure if it's a problem related to jQuery. In hopes that some jQuery experts can shed some light on this. The code snippet below was included in my HTML page to automatica ...

I desire to receive comments only once since they are being rehashed repeatedly

On the server-side: This is where I retrieve the comment from the server db.postSchema .findOne({ _id: comment.post }) .populate("owner") .exec((err, users) => { for (let i = 0; i < ...

Tips for configuring Webstorm to automatically change double quotes to single quotes when reformatting source code

After using cmd + alt + l in Webstorm to format my JavaScript code, I noticed that double quotes are used instead of single quotes. How can I configure Webstorm to automatically change the double quotes to single quotes in my code? ...

Retrieve a file from an AWS S3 bucket using AngularJS

Currently utilizing angularjs. I am in need of incorporating a download feature. <button class="btn btn-labeled btn-info" title="download"> <a href="link provided by s3" download="downloaded">Download</a> </button> I have ...

Troubleshooting: Why is the AngularUI Modal dialog malfunctioning

I'm currently working on integrating an angularUI modular dialog into my application. Here is a snippet from my controller.js file: define([ 'app' ], function(app) { app.controller('TeacherClasses', [ '$scope', &apo ...

Issues arise when Angular Meteor fails to load the UI-Router properly

Currently, I am exploring the integration of ui-router for routing within a meteor-angular application. My reference point is the meteor Whatsapp tutorial which can be found here Below is the relevant code snippet related to ui-router implementation: log ...

Utilize Javascript to acquire the redirected URL

Seeking assistance with making a GET call to an API endpoint that redirects me. I have enabled CORS to access the Location, but struggling to find a way through Ajax or Fetch to retrieve only the Redirect URL. Any help would be highly appreciated. ...

AngularJS scope refreshed following search form validation in Symfony2

Hey there, fellow developers! We are currently faced with the task of rewriting a software application in Symfony2 using AngularJS. We have chosen to utilize Symfony2 for its robust MVC capabilities and AngularJS for its powerful functions. Our current c ...

The parameter type (key: string, id: string, pagination: number) in the argument does not match the expected type of Boolean for the parameter

I'm facing an issue while trying to implement the following documentation: https://swr.vercel.app/ using my own setup: import React, { useEffect } from 'react' import PatientsTable from 'components/patients/PatientsTable' import ...

Is there a way to utilize JSON data to dynamically fill column names in a JQuery datatable?

JSON Data: { "data": [ { "name": "Garrett Winters", "designation": "Accountant", "salary": "$170,750", }, { "name": "Brielle Williamson", "designation": "Integration Specialist", "salary": "$372,000", } ] } H ...

Tips on sending error messages to an MVC view during an Ajax call

When using ajax to call a controller action method on an MVC button click event, there may be validation logic in the controller that needs to notify the user of any errors. Is there a way to send an error message to the ajax success event from the control ...

show button after the page has finished loading

I have a button similar to this: <input type="submit" id="product_197_submit_button" class="wpsc_buy_button" name="Buy" value="Add To Cart"> However, I am encountering an issue where if the user clicks the button before all scripts are loaded, an e ...

What is the best way to showcase the outcomes of arithmetic calculations on my calculator?

In the midst of creating a calculator, I have encountered some issues in getting it to display the correct result. Despite successfully storing the numbers clicked into separate variables, I am struggling with showing the accurate calculation outcome. l ...

The most effective method for adding data to a <pre /> element is through VueJS

I have an electron app that executes a program and stores the output when data is received. My goal is to showcase the content of this output within an html pre element. One approach I can take is to create a variable and continuously add the output data ...

Ways to verify if an ajax function is currently occupied by a previous request

Is there a way to determine if an ajax function is occupied by a prior call? What measures can be taken to avoid invoking an ajax function while it is still processing a previous request with a readyState != 4 status? ...

Manipulate sibling elements using jQuery's addClass and remove methods

I have implemented a function that adds the class active to elements when they reach the top of the browser, ensuring that the next element will scroll in over the top. While this works smoothly in Chrome, I am encountering some jumping behavior when testi ...

Can you explain the process behind /^image/w+/.test(file.type)?

I came across this piece of code that I'm testing to determine if a file added to a canvas is an image. I'm curious about the functionality behind it. Just to clarify, "file" refers to a FileList obtained from an input element. if (/^image\ ...

Injecting Dependencies Into ExpressJS Routes Middleware

Hey there! I'm currently working on injecting some dependencies into an expressjs route middleware. Usually, in your main application, you would typically do something like this: const express = require('express'); const userRouter = requi ...