Advertisement
RapidMod

Angular Increment Counter

Feb 23rd, 2020 (edited)
456
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Angular Increment Counter Component
  3.  * Author: RapidMod
  4.  * Website: https://rapidmod.io/
  5.  *
  6.  * Description:
  7.  * This Angular component features an increment counter that operates based on predefined increments and intervals,
  8.  * showcasing dynamic "Go" and "Stop" states. It demonstrates the use of async/await patterns within Angular for
  9.  * managing timing and state transitions in a web application. The component utilizes a utility function for delays,
  10.  * iterates over a predefined array of increments to manage counter states, and provides a method for a continuous counter
  11.  * based on component state.
  12.  *
  13.  * Key Functions:
  14.  * - ngOnInit: Component initialization, invoking item retrieval and counter operations.
  15.  * - wait: Utility to create a delay using Promises.
  16.  * - intervalCounter: Processes an array of increments, applying "Go" or "Stop" states with varying intervals.
  17.  * - startCounter: Initiates a continuous counter that increments until a "Stopped" state is encountered.
  18.  *
  19.  * The component is designed for demonstration purposes, highlighting asynchronous operations in Angular components.
  20.  * The implementation details are provided by RapidMod, showcasing best practices for asynchronous JavaScript in Angular.
  21.  */
  22.  
  23.   ngOnInit() {
  24.     this.getItems();
  25.  
  26.     this.intervalCounter(text => console.log(text));
  27.     this.startCounter(text => console.log(text));
  28.   }
  29.  
  30.  
  31.   wait = (ms) => new Promise(res => setTimeout(res, ms));
  32.  
  33.   //foreach these in interval counter
  34.   increments = [
  35.     {label:'Go',val:3000},
  36.     {label:'Stop',val:2000},
  37.     {label:'Go',val:1000},
  38.     {label:'Stop',val:3000},
  39.     {label:'Go',val:4000},
  40.     {label:'Stop',val:1000},
  41.  
  42.   ];
  43.  
  44.   intervalCounter = async callback => {
  45.   this.counterStatus = "Active";
  46.  
  47.   for (const increment of this.increments) {
  48.     callback(increment.label);
  49.     await this.wait(increment.val);
  50.   }
  51.  
  52.   this.counterStatus = "Complete";
  53.   callback('Complete');
  54. };
  55.  
  56.   //second counter
  57.   counterStatus = "Stopped";
  58.   startCounter = async callback => {
  59.     let i = 0;
  60.     while (this.counterStatus !== 'Stopped'){
  61.       callback(i);
  62.       await this.wait(1000);
  63.       i++;
  64.     }
  65.   };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement