Timer.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCore/Timer.h>
  7. #include <LibJS/Runtime/Object.h>
  8. #include <LibWeb/HTML/Timer.h>
  9. #include <LibWeb/HTML/Window.h>
  10. namespace Web::HTML {
  11. JS_DEFINE_ALLOCATOR(Timer);
  12. JS::NonnullGCPtr<Timer> Timer::create(JS::Object& window_or_worker_global_scope, i32 milliseconds, Function<void()> callback, i32 id)
  13. {
  14. auto heap_function_callback = JS::create_heap_function(window_or_worker_global_scope.heap(), move(callback));
  15. return window_or_worker_global_scope.heap().allocate_without_realm<Timer>(window_or_worker_global_scope, milliseconds, heap_function_callback, id);
  16. }
  17. Timer::Timer(JS::Object& window_or_worker_global_scope, i32 milliseconds, JS::NonnullGCPtr<JS::HeapFunction<void()>> callback, i32 id)
  18. : m_window_or_worker_global_scope(window_or_worker_global_scope)
  19. , m_callback(move(callback))
  20. , m_id(id)
  21. {
  22. m_timer = Core::Timer::create_single_shot(milliseconds, [this] {
  23. m_callback->function()();
  24. }).release_value_but_fixme_should_propagate_errors();
  25. }
  26. void Timer::visit_edges(Cell::Visitor& visitor)
  27. {
  28. Base::visit_edges(visitor);
  29. visitor.visit(m_window_or_worker_global_scope);
  30. visitor.visit(m_callback);
  31. }
  32. Timer::~Timer()
  33. {
  34. VERIFY(!m_timer->is_active());
  35. }
  36. void Timer::start()
  37. {
  38. m_timer->start();
  39. }
  40. void Timer::stop()
  41. {
  42. m_timer->stop();
  43. }
  44. }