Is it possible that JavaScript setTimeout() fires earlier?

  Kiến thức lập trình

I wrote a utility function to create an async timeout:

export function asyncTimeout(timeout: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, timeout))
}

I also wrote a unit test by vitest:

test('asyncTimeout', async ()=> {
  const start = Date.now()
  await asyncTimeout(10)
  const end = Date.now()
  expect(end - start).toBeGreaterThanOrEqual(10)
})

Most of the time this test is being passed.
But it fails rarely.

screenshot of unit test failure

How that possible? Is it possible that setTimeout fires earlier than the specified time according to event loop?

1

LEAVE A COMMENT