DEV Community

loading...

How setTimeout working?

ihavecoke profile image mixbo ・2 min read

Alt Text

If you write code in javascript, you must be used setTimeout method.
sometimes it's cool and just execution callback delay.

Do you know how setTimeout working? let's review

const foo = ()=>{
  setTimeout(()=>{
    console.log('foo...')
  }, 1000)
}

const bar = ()=>{
  setTimeout(()=>{
    console.log('bar...')
  },0)
}

foo()
bar()

// 
undefined
bar...
foo..

As you can see just output undefined first bar... and foo... last. why undefined first?

Call foo and bar method haven't return anythings so undefined will be finally.

But why bar... before foo...? i just call method bar() after foo()?

Let's see setTimeout implement in V8 engines


struct DelayTask{
  int64 id
  CallBackFunction cbf;
  int start_time;
  int delay_time;
};
DelayTask timerTask;
timerTask.cbf = showName;
timerTask.start_time = getCurrentTime(); // get current time
timerTask.delay_time = 200;//delay time

DelayTask defined struct includes id, CallBackFunction, start_time and delay_time.

id can call or stop task.
CallBackFunction callback just defined delay times will do actions

So far how setTimeout working? we can also found source code


void ProcessTimerTask(){
  // get delayed_incoming_queue task witch time matched 
  // then one by one execution
}

TaskQueue task_queue
void ProcessTask();
bool keep_running = true;
void MainTherad(){
  for(;;){
    // Do messages queue tasks 
    Task task = task_queue.takeTask();
    ProcessTask(task);

    // Do Delay queue tasks 
    ProcessDelayTask()

    if(!keep_running) 
        break; 
  }
}

MainTheread have loop action will call message queue and delay task queue. this is why sometime call setTimeout you can found some dom element or some http request response. because setTimeout just in delay queue and execution after message queue

PS: message queue like some http request, dom render, mouse event, keyboard event etc.

Now why demo code output bar... before foo...? Emmmm bar just delay 0 and foo delay 1000 so bar shorter than foo call first bar last foo.

Hope can help you :)

Discussion (0)

Forem Open with the Forem app