Advertisement
twokay

lit task autorun

Apr 20th, 2024
904
0
150 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 2.26 KB | Source Code | 0 0
  1. import {html, LitElement} from 'lit';
  2. import {customElement, property} from 'lit/decorators.js';
  3. import "../components/dnsentry"
  4. import {Task} from "@lit/task";
  5. import type {HeartbeatResponse, HeartbeatRequest} from "../types/heartbeat";
  6.  
  7. const controller = new AbortController();
  8. const signal = controller.signal;
  9. const heartbeatTimer = setInterval
  10.  
  11. @customElement('heartbeat-page')
  12. export class HeartBeat extends LitElement {
  13.   @property({type: String})
  14.   entryId = ""
  15.  
  16.   private heartbeatInterval:number = 0
  17.   private heartbeatCounter:number = 0
  18.  
  19.   // @function createRequestData
  20.   // @description creates the body content for the request
  21.   private createRequestData(): HeartbeatRequest {
  22.     const d = new Date();
  23.     let time = d.getTime();
  24.     return {
  25.       clientclock: time
  26.     }
  27.   }
  28.  
  29.   // @function createRequestConfig
  30.   // @description creates the configuration used in a fetch request
  31.   private createRequestConfig(): RequestInit {
  32.     return {
  33.       method: "POST",
  34.       headers: {
  35.         'Accept': 'application/json',
  36.         'Content-Type': 'application/json',
  37.       },
  38.       body: JSON.stringify(this.createRequestData()),
  39.       credentials: 'include',
  40.       signal
  41.     }
  42.   }
  43.  
  44.   private createRequest(): Promise<HeartbeatResponse> {
  45.     return new Promise<HeartbeatResponse>((resolve, reject) => {
  46.       let test = fetch(`https://dns.api.local.entitywind.io/dns/${this.entryId}`, this.createRequestConfig())
  47.     })
  48.   }
  49.  
  50.   private _entryTask = new Task(this, {
  51.     task: async ([counter], {signal}) => {
  52.       return this.createRequest()
  53.     },
  54.     args: () => [this.heartbeatCounter]
  55.   });
  56.  
  57.   private stopHeartbeatTimer() {
  58.     clearInterval(this.heartbeatInterval)
  59.   }
  60.  
  61.   private updateHeartbeat() {
  62.     if (this.heartbeatCounter===undefined) {
  63.       this.heartbeatCounter = 0
  64.     }
  65.     this.heartbeatCounter++
  66.   }
  67.  
  68.   private startHeartbeatTimer() {
  69.     this.heartbeatInterval = setInterval(this.updateHeartbeat, 1000)
  70.   }
  71.  
  72.   render() {
  73.     return html`
  74.       <div>
  75.         <p>heartbeat page</p>
  76.         <button class="abort" @click="${()=>this.stopHeartbeatTimer()}">Stop</button>
  77.         <button class="abort" @click="${()=>this.startHeartbeatTimer()}">Start</button>
  78.         <p></p>
  79.       </div>
  80.     `
  81.   }
  82. }
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement