I was playing with libuv and quickjs(JS engine). And implementing setTimeout function using its core JSRuntime.
My JS code looks like below, which run synchronously rather than in async fashion as it should:
console.log("Start");
//this setTimeout will block and , end will be run only once this finish
setTimeout(()=>{
console.log('Timeout has run');
},5000);
console.log("End");
The output of this program is :
Start
Timeout has run
*****This one runs after 5 second*******
End
My Libuv code is as such (not exactly like this, but somewhat like this):
int setup_setTimeout(uv_loop_t *loop){
uv_timer_t* timer_req=(uv_timer_t*)malloc(sizeof(uv_timer_t));//without this I get segmentation error, as in my timerCallback it seems t be lost
uv_timer_init(loop, timer_req);
uv_timer_start(timer_req,timerCallback,delay,0);
uv_run(loop, UV_RUN_DEFAULT);
std::cout<<"*****This one runs after 5 second*******"<<std::endl;
}
I am a noob (with libuv usage), and hence is in doubt if there is something I am missing or running it wrong. As the code seems to run synhronously rather than in async fashion.
Ok , so I found the solution. As I have not posted the full code, I wil try to explain how I resolved the issue.
uv_run(loop, UV_RUN_DEFAULT);should be run after JS script evaluation.uv_run, it will start looking for events it needs to process and the only event it is waiting for is the timer thing, and hence it will start running it.uv_run.