@@ -34,23 +34,26 @@ namespace Babylon::Polyfills::Internal
3434 Timeout (Timeout&&) = delete ;
3535 };
3636
37- TimeoutDispatcher::TimeoutDispatcher (Babylon::JsRuntimeScheduler& runtimeScheduler )
38- : m_runtimeScheduler{runtimeScheduler }
37+ TimeoutDispatcher::TimeoutDispatcher (Babylon::JsRuntime& runtime )
38+ : m_runtimeScheduler{runtime }
3939 , m_thread{std::thread{&TimeoutDispatcher::ThreadFunction, this }}
4040 {
4141 }
4242
4343 TimeoutDispatcher::~TimeoutDispatcher ()
4444 {
4545 {
46- std::unique_lock<std::mutex> lk {m_mutex};
46+ std::unique_lock<std::mutex> lock {m_mutex};
4747 m_idMap.clear ();
4848 m_timeMap.clear ();
4949 }
5050
51- m_shutdown = true ;
51+ m_cancellationSource. cancel () ;
5252 m_condVariable.notify_one ();
5353 m_thread.join ();
54+
55+ // Wait for async operations to complete.
56+ m_runtimeScheduler.Rundown ();
5457 }
5558
5659 TimeoutDispatcher::TimeoutId TimeoutDispatcher::Dispatch (std::shared_ptr<Napi::FunctionReference> function, std::chrono::milliseconds delay)
@@ -71,7 +74,8 @@ namespace Babylon::Polyfills::Internal
7174
7275 if (time <= earliestTime)
7376 {
74- m_runtimeScheduler.Get ()([this ]() {
77+ m_runtimeScheduler.Get ()([this ]()
78+ {
7579 m_condVariable.notify_one ();
7680 });
7781 }
@@ -123,11 +127,11 @@ namespace Babylon::Polyfills::Internal
123127
124128 void TimeoutDispatcher::ThreadFunction ()
125129 {
126- while (!m_shutdown )
130+ while (!m_cancellationSource. cancelled () )
127131 {
128- std::unique_lock<std::mutex> lk{m_mutex};
129- TimePoint nextTimePoint{};
132+ std::unique_lock<std::mutex> lock{m_mutex};
130133
134+ TimePoint nextTimePoint{};
131135 while (!m_timeMap.empty ())
132136 {
133137 nextTimePoint = m_timeMap.begin ()->second ->time ;
@@ -136,7 +140,7 @@ namespace Babylon::Polyfills::Internal
136140 break ;
137141 }
138142
139- m_condVariable.wait_until (lk , nextTimePoint);
143+ m_condVariable.wait_until (lock , nextTimePoint);
140144 }
141145
142146 while (!m_timeMap.empty () && m_timeMap.begin ()->second ->time == nextTimePoint)
@@ -147,9 +151,9 @@ namespace Babylon::Polyfills::Internal
147151 m_idMap.erase (timeout->id );
148152 }
149153
150- while (!m_shutdown && m_timeMap.empty ())
154+ while (!m_cancellationSource. cancelled () && m_timeMap.empty ())
151155 {
152- m_condVariable.wait (lk );
156+ m_condVariable.wait (lock );
153157 }
154158 }
155159 }
@@ -159,7 +163,9 @@ namespace Babylon::Polyfills::Internal
159163 if (function)
160164 {
161165 m_runtimeScheduler.Get ()([function = std::move (function)]()
162- { function->Call ({}); });
166+ {
167+ function->Call ({});
168+ });
163169 }
164170 }
165171}
0 commit comments