summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibWeb/RequestIdleCallback/IdleDeadline.cpp
blob: 2012c50ac64461a9e4cd6ff290c28596f8cb9c0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
 * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
 * Copyright (c) 2022, the SerenityOS developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/RequestIdleCallback/IdleDeadline.h>

namespace Web::RequestIdleCallback {

JS::NonnullGCPtr<IdleDeadline> IdleDeadline::create(HTML::Window& window, bool did_timeout)
{
    return *window.heap().allocate<IdleDeadline>(window.realm(), window, did_timeout);
}

IdleDeadline::IdleDeadline(HTML::Window& window, bool did_timeout)
    : PlatformObject(window.realm())
    , m_did_timeout(did_timeout)
{
    set_prototype(&window.cached_web_prototype("IdleDeadline"));
}

IdleDeadline::~IdleDeadline() = default;

// https://w3c.github.io/requestidlecallback/#dom-idledeadline-timeremaining
double IdleDeadline::time_remaining() const
{
    auto const& event_loop = HTML::main_thread_event_loop();
    // 1. Let now be a DOMHighResTimeStamp representing current high resolution time in milliseconds.
    auto now = event_loop.unsafe_shared_current_time();
    // 2. Let deadline be the result of calling IdleDeadline's get deadline time algorithm.
    auto deadline = event_loop.compute_deadline();
    // 3. Let timeRemaining be deadline - now.
    auto time_remaining = deadline - now;
    // 4. If timeRemaining is negative, set it to 0.
    if (time_remaining < 0)
        time_remaining = 0;
    // 5. Return timeRemaining.
    // NOTE: coarsening to milliseconds
    return ceil(time_remaining);
}

}