summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibWeb/DOM/Timer.cpp
blob: 4ef944a9eb507f359d1177053a03ee7841838c65 (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/Function.h>
#include <LibWeb/DOM/Timer.h>
#include <LibWeb/DOM/Window.h>

namespace Web::DOM {

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

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

Timer::Timer(Window& window, Type type, int milliseconds, JS::Function& callback)
    : m_window(window)
    , m_type(type)
    , m_callback(JS::make_handle(&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);
}

}