HeapTimer.cpp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (c) 2024, Tim Flynn <trflynn89@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCore/Timer.h>
  7. #include <LibWeb/WebDriver/HeapTimer.h>
  8. namespace Web::WebDriver {
  9. GC_DEFINE_ALLOCATOR(HeapTimer);
  10. HeapTimer::HeapTimer()
  11. : m_timer(Core::Timer::create())
  12. {
  13. }
  14. HeapTimer::~HeapTimer() = default;
  15. void HeapTimer::visit_edges(JS::Cell::Visitor& visitor)
  16. {
  17. Base::visit_edges(visitor);
  18. visitor.visit(m_on_timeout);
  19. }
  20. void HeapTimer::start(u64 timeout_ms, GC::Ref<GC::Function<void()>> on_timeout)
  21. {
  22. m_on_timeout = on_timeout;
  23. m_timer->on_timeout = [this]() {
  24. m_timed_out = true;
  25. if (m_on_timeout) {
  26. m_on_timeout->function()();
  27. m_on_timeout = nullptr;
  28. }
  29. };
  30. m_timer->set_interval(static_cast<int>(timeout_ms));
  31. m_timer->set_single_shot(true);
  32. m_timer->start();
  33. }
  34. void HeapTimer::stop_and_fire_timeout_handler()
  35. {
  36. auto on_timeout = m_on_timeout;
  37. stop();
  38. if (on_timeout)
  39. on_timeout->function()();
  40. }
  41. void HeapTimer::stop()
  42. {
  43. m_on_timeout = nullptr;
  44. m_timer->stop();
  45. }
  46. }