Advertisement
avr39ripe

jsBaseTickerFuncBasedClass

Mar 10th, 2021
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>Study</title>
  6. </head>
  7. <body>
  8.     <script>
  9.         `use strict`
  10.  
  11.         function Ticker(tickerId, baseDelay = 3000, ticksCount = 10, onTimeout = undefined ) {
  12.             this.tickerId = tickerId;
  13.             this.delay = baseDelay;
  14.             this.ticksCount = ticksCount;
  15.             this.cnt = 0;
  16.            
  17.             this.arm = function () {
  18.                 this.cnt = 0;
  19.                 this.id = setTimeout(function ticker(object) {
  20.                     console.log(`Ticker #${object.tickerId} ${object.cnt}`);
  21.                     (object.cnt++) % 2 ? object.delay *= 2 : object.delay /= 2;
  22.                     if (object.cnt == object.ticksCount && object.ticksCount != -1)
  23.                     {
  24.                         clearTimeout(object.id);
  25.                         if (object.onTimeout) { object.onTimeout();}
  26.                     }
  27.                     else { object.id = setTimeout(ticker, object.delay, object); };
  28.                 }, this.delay, this);
  29.                 return this;
  30.             }
  31.  
  32.             this.disarm = function () {
  33.                 clearTimeout(this.id);
  34.                 return this;
  35.             }
  36.  
  37.             this.set = function (baseDelay = 3000, ticksCount = 10) {
  38.                 this.delay = baseDelay;
  39.                 this.ticksCount = ticksCount;
  40.                 return this;
  41.             }
  42.  
  43.             this.setOntimeout= function(onTimeout)
  44.             {
  45.                 this.onTimeout = onTimeout;
  46.             }
  47.  
  48.         }
  49.  
  50.         {
  51.             let t1 = new Ticker(26);
  52.             let t2 = new Ticker(42);
  53.  
  54.             t2.setOntimeout(() => { console.log('t2 finished ticking!') });
  55.             t2.set(1000, 8).arm();
  56.             t1.set(2500, 20).arm();
  57.  
  58.             setTimeout(() => { t1.disarm() }, 8000);
  59.         }
  60.  
  61.     </script>
  62. </body>
  63. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement