timer_emscripten.monkey2 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #If __TARGET__="emscripten"
  2. #Import "<emscripten>"
  3. Namespace std.timer
  4. Private
  5. Using std.time
  6. Using std.collections
  7. Using emscripten
  8. 'GC protection!
  9. Global _timers:=New Map<Timer,Bool>
  10. Public
  11. 'Have to poll with emscripten...
  12. '
  13. Class Timer
  14. Method New( hertz:Double,fired:Void() )
  15. _period=1/hertz
  16. _timeout=Now()+_period
  17. _fired=fired
  18. _context.timer=self
  19. emscripten_async_call( Callback,Cast<Byte Ptr>( Varptr _context ),_period * 1000 )
  20. _timers[Self]=True
  21. End
  22. Property Suspended:Bool()
  23. Return _suspended
  24. Setter( suspended:Bool )
  25. _suspended=suspended
  26. End
  27. Method Cancel()
  28. _cancelled=True
  29. End
  30. Private
  31. Struct Context
  32. Field timer:Timer
  33. End
  34. Field _period:Double
  35. Field _timeout:Double
  36. Field _fired:Void()
  37. Field _suspended:Bool
  38. Field _cancelled:Bool
  39. Field _context:Context
  40. Function Callback( arg:Void Ptr )
  41. Local context:=Cast<Context Ptr>( arg )
  42. context->timer.Update()
  43. End
  44. Method Update()
  45. While Not _cancelled
  46. Local now:=Now()
  47. Local sleep:=Int((_timeout-now)*1000)
  48. If sleep>0
  49. emscripten_async_call( Callback,Cast<Byte Ptr>( Varptr _context ),sleep )
  50. Return
  51. Endif
  52. If Not _suspended _fired()
  53. _timeout+=_period
  54. Wend
  55. _timers.Remove( Self )
  56. End
  57. End
  58. #Endif