IdleDeadline.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. JS::NonnullGCPtr<IdleDeadline> IdleDeadline::create(JS::Realm& realm, bool did_timeout)
  13. {
  14. return *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. set_prototype(&Bindings::cached_web_prototype(realm, "IdleDeadline"));
  21. }
  22. IdleDeadline::~IdleDeadline() = default;
  23. // https://w3c.github.io/requestidlecallback/#dom-idledeadline-timeremaining
  24. double IdleDeadline::time_remaining() const
  25. {
  26. auto const& event_loop = HTML::main_thread_event_loop();
  27. // 1. Let now be a DOMHighResTimeStamp representing current high resolution time in milliseconds.
  28. auto now = HighResolutionTime::unsafe_shared_current_time();
  29. // 2. Let deadline be the result of calling IdleDeadline's get deadline time algorithm.
  30. auto deadline = event_loop.compute_deadline();
  31. // 3. Let timeRemaining be deadline - now.
  32. auto time_remaining = deadline - now;
  33. // 4. If timeRemaining is negative, set it to 0.
  34. if (time_remaining < 0)
  35. time_remaining = 0;
  36. // 5. Return timeRemaining.
  37. // NOTE: coarsening to milliseconds
  38. return ceil(time_remaining);
  39. }
  40. }