Skip to content

d8corp/sync-timer

Repository files navigation

sync-timer

 

NPM downloads changelog license

Abstract

This library gives new way to create macrotasks. setTimeout does not ensure callback calls in the same macrotask, this is the difference. This library make you sure callback with the same delay will be run in the same queue.

stars watchers

Install

npm i sync-timer

Usage

SyncTimer has the same arguments as setTimeout, but this is a class.

import SyncTimer from 'sync-timer'

const timer = new SyncTimer(() => {
  console.log('Hello World!')
}, 1000)

timer.cancel()

If you try the next example, you get this logs:

1, 2, 3

setTimeout(() => {
  console.log(1)
})

setTimeout(() => {
  queueMicrotask(() => {
    console.log(2)
  })
})

setTimeout(() => {
  console.log(3)
})

That's because of each setTimeout creates separate macrotask with own microtasks queue.

SyncTimer calls every timer (used in the same macrotask with the same timeout) in one macrotask.

new SyncTimer(() => {
  console.log(1)
})

new SyncTimer(() => {
  queueMicrotask(() => {
    console.log(2)
  })
})

new SyncTimer(() => {
  console.log(3)
})

returns 1, 3, 2

Issues

If you find a bug or have a suggestion, please file an issue on GitHub.

issues

About

The same as setTimeout, but callbacks run synchronously

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published