summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibWeb/DOM/Timer.cpp
blob: 5e5afbd50b8ce7c0a66ae541063fa9c68e76a7f0 (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
/*
 * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibCore/Timer.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibWeb/DOM/Timer.h>
#include <LibWeb/DOM/Window.h>

namespace Web::DOM {

NonnullRefPtr<Timer> Timer::create_interval(Window& window, int milliseconds, NonnullOwnPtr<Bindings::CallbackType> callback)
{
    return adopt_ref(*new Timer(window, Type::Interval, milliseconds, move(callback)));
}

NonnullRefPtr<Timer> Timer::create_timeout(Window& window, int milliseconds, NonnullOwnPtr<Bindings::CallbackType> callback)
{
    return adopt_ref(*new Timer(window, Type::Timeout, milliseconds, move(callback)));
}

Timer::Timer(Window& window, Type type, int milliseconds, NonnullOwnPtr<Bindings::CallbackType> callback)
    : m_window(window)
    , m_type(type)
    , m_callback(move(callback))
{
    m_id = window.allocate_timer_id({});
    m_timer = Core::Timer::construct(milliseconds, [this] { m_window.timer_did_fire({}, *this); });
    if (m_type == Type::Timeout)
        m_timer->set_single_shot(true);
}

Timer::~Timer()
{
    m_window.deallocate_timer_id({}, m_id);
}

}