timer.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. @external("env", "wasm_create_timer")
  6. declare function wasm_create_timer(a: i32, b: bool, c: bool): i32;
  7. @external("env", "wasm_timer_cancel")
  8. declare function wasm_timer_cancel(a: i32): void;
  9. @external("env", "wasm_timer_restart")
  10. declare function wasm_timer_restart(a: i32, b: i32): void;
  11. @external("env", "wasm_get_sys_tick_ms")
  12. declare function wasm_get_sys_tick_ms(): i32;
  13. export var timer_list = new Array<user_timer>();
  14. export class user_timer {
  15. timer_id: i32 = 0;
  16. timeout: i32;
  17. period: bool = false;
  18. cb: () => void;
  19. constructor(cb: () => void, timeout: i32, period: bool) {
  20. this.cb = cb;
  21. this.timeout = timeout;
  22. this.period = period
  23. this.timer_id = timer_create(this.timeout, this.period, true);
  24. }
  25. }
  26. export function timer_create(a: i32, b: bool, c: bool): i32 {
  27. return wasm_create_timer(a, b, c);
  28. }
  29. export function setTimeout(cb: () => void, timeout: i32): user_timer {
  30. var timer = new user_timer(cb, timeout, false);
  31. timer_list.push(timer);
  32. return timer;
  33. }
  34. export function setInterval(cb: () => void, timeout: i32): user_timer {
  35. var timer = new user_timer(cb, timeout, true);
  36. timer_list.push(timer);
  37. return timer;
  38. }
  39. export function timer_cancel(timer: user_timer): void {
  40. wasm_timer_cancel(timer.timer_id);
  41. var i = 0;
  42. for (i = 0; i < timer_list.length; i++) {
  43. if (timer_list[i].timer_id == timer.timer_id)
  44. break;
  45. }
  46. timer_list.splice(i, 1);
  47. }
  48. export function timer_restart(timer: user_timer, interval: number): void {
  49. wasm_timer_restart(timer.timer_id, i32(interval));
  50. }
  51. export function now(): i32 {
  52. return wasm_get_sys_tick_ms();
  53. }
  54. // This export function need to be copied to the top application file
  55. //
  56. export function on_timer_callback(on_timer_id: i32): void {
  57. for (let i = 0; i < timer_list.length; i++) {
  58. if (timer_list[i].timer_id == on_timer_id) {
  59. timer_list[i].cb();
  60. }
  61. }
  62. }