-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathtimer.cpp
More file actions
85 lines (70 loc) · 2.13 KB
/
timer.cpp
File metadata and controls
85 lines (70 loc) · 2.13 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright (c) 2012 Plenluno All rights reserved.
#include <libnode/timer.h>
#include <libnode/detail/uv/timer.h>
namespace libj {
namespace node {
namespace {
const UInt TIMEOUT_MAX = 2147483647; // 2^31-1
class OnTimeout : LIBJ_JS_FUNCTION(OnTimeout)
public:
OnTimeout(
JsFunction::Ptr callback,
JsArray::Ptr args,
detail::uv::Timer* timer,
Boolean repeat)
: callback_(callback)
, args_(args)
, timer_(timer)
, repeat_(repeat) {}
Value operator()(JsArray::Ptr args) {
(*callback_)(args_);
if (!repeat_) {
timer_->close();
}
return libj::Status::OK;
}
private:
JsFunction::Ptr callback_;
JsArray::Ptr args_;
detail::uv::Timer* timer_;
Boolean repeat_;
};
} // namespace
Value setTimeout(JsFunction::Ptr callback, UInt delay, JsArray::Ptr args) {
if (!callback) return UNDEFINED;
if (delay == 0 || delay > TIMEOUT_MAX) delay = 1;
detail::uv::Timer* timer = new detail::uv::Timer();
OnTimeout::Ptr onTimeout(new OnTimeout(callback, args, timer, false));
timer->setOnTimeout(onTimeout);
timer->start(delay, 0);
return timer;
}
Value setInterval(JsFunction::Ptr callback, UInt delay, JsArray::Ptr args) {
if (!callback) return UNDEFINED;
if (delay == 0 || delay > TIMEOUT_MAX) delay = 1;
detail::uv::Timer* timer = new detail::uv::Timer();
OnTimeout::Ptr onTimeout(new OnTimeout(callback, args, timer, true));
timer->setOnTimeout(onTimeout);
timer->start(delay, delay);
return timer;
}
Boolean clearTimeout(const Value& timeoutId) {
detail::uv::Timer* timer = to<detail::uv::Timer*>(timeoutId);
if (timer) {
timer->close();
return true;
} else {
return false;
}
}
Boolean clearInterval(const Value& intervalId) {
detail::uv::Timer* timer = to<detail::uv::Timer*>(intervalId);
if (timer) {
timer->close();
return true;
} else {
return false;
}
}
} // namespace node
} // namespace libj