If Javascript is single threaded, how things like a clock work?

Viewed 60

I mean, maybe I'm wrong and totally not understanding what single threaded means, but I'm just wondering: How can a clock continuously work in a web page while users interact with other things on the same page without the clock stopping?

I refer to clock as an example, but it can be any kind of element or elements working at the same time

1 Answers

Here is an analogy, probably not the best, but I hope it helps you to understand :


Imagine you are a single mum at home with three kids. It's monday morning and you have to prepare them for school.

All you have to do :

  • You have to feed kid A, B and C
  • You have to dress kid A, B and C
  • You have to find your bag
  • Find your car keys
  • You have to make yourself a coffee and drink it
  • Dress your hair

As you imagine it won't be easy, and won't be linear. The mum won't be able to perform one task after one task, she will perform multiple tasks in parallel :

start to make herself a coffee, when at the same time she put the kid A shoes on and reprimand kid B that is annoying.

Every tasks will be performed in parallel and in multiple steps (Maybe it will take her 5 time to finish dressing kid A).

Now imagine that the computer is an extraordinary fast mum (a 1Ghz processor will performs 1.000.000.000 operation per second).

Related