IdleDeadline.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  8. #include <LibWeb/HTML/Window.h>
  9. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  10. #include <LibWeb/RequestIdleCallback/IdleDeadline.h>
  11. namespace Web::RequestIdleCallback {
  12. WebIDL::ExceptionOr<JS::NonnullGCPtr<IdleDeadline>> IdleDeadline::create(JS::Realm& realm, bool did_timeout)
  13. {
  14. return MUST_OR_THROW_OOM(realm.heap().allocate<IdleDeadline>(realm, realm, did_timeout));
  15. }
  16. IdleDeadline::IdleDeadline(JS::Realm& realm, bool did_timeout)
  17. : PlatformObject(realm)
  18. , m_did_timeout(did_timeout)
  19. {
  20. }
  21. JS::ThrowCompletionOr<void> IdleDeadline::initialize(JS::Realm& realm)
  22. {
  23. MUST_OR_THROW_OOM(Base::initialize(realm));
  24. set_prototype(&Bindings::ensure_web_prototype<Bindings::IdleDeadlinePrototype>(realm, "IdleDeadline"));
  25. return {};
  26. }
  27. IdleDeadline::~IdleDeadline() = default;
  28. // https://w3c.github.io/requestidlecallback/#dom-idledeadline-timeremaining
  29. double IdleDeadline::time_remaining() const
  30. {
  31. auto const& event_loop = HTML::main_thread_event_loop();
  32. // 1. Let now be a DOMHighResTimeStamp representing current high resolution time in milliseconds.
  33. auto now = HighResolutionTime::unsafe_shared_current_time();
  34. // 2. Let deadline be the result of calling IdleDeadline's get deadline time algorithm.
  35. auto deadline = event_loop.compute_deadline();
  36. // 3. Let timeRemaining be deadline - now.
  37. auto time_remaining = deadline - now;
  38. // 4. If timeRemaining is negative, set it to 0.
  39. if (time_remaining < 0)
  40. time_remaining = 0;
  41. // 5. Return timeRemaining.
  42. // NOTE: coarsening to milliseconds
  43. return ceil(time_remaining);
  44. }
  45. }