Last active
August 29, 2015 14:08
-
-
Save ando-takahiro/7e100bc4d0014f6a2eee to your computer and use it in GitHub Desktop.
THIS HAS BUGS: JS's setTimeout in C++ on libuv
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename Fn> | |
void set_timeout(Fn fn, uint64_t timeout, uv_loop_t* l = nullptr) { | |
struct payload { | |
uv_timer_t timer; | |
Fn fn; | |
payload(Fn&& f) : fn(f) {} | |
}; | |
payload* p = new payload(std::move(fn)); | |
if (!l) { | |
l = uv_default_loop(); | |
} | |
uv_timer_init(l, &p->timer); | |
p->timer.data = p; | |
uv_timer_start(&p->timer, | |
[](uv_timer_t* handle) { | |
payload* p = (payload*)handle->data; | |
p->fn(); | |
uv_close((uv_handle_t*)handle, [](uv_handle_t* h){ | |
payload* p = (payload*)h->data; | |
delete p; // it seems that we can not delete here, inside of uv_close handler | |
}); | |
}, | |
timeout, | |
0); | |
} | |
set_timeout([]() { | |
printf("hello after 10 ms"); | |
}, 10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment