Giter Club home page Giter Club logo

timer's Introduction

@colyseus/timer

Timing Events tied to colyseus/clock.

ClockTimer is a subclass of Clock, which adds methods to handle timeout and intervals relying on Clock's ticks.

Why?

Once built-in setTimeout and setInterval relies on CPU load, functions may delay an unexpected amount of time to execute. Having it tied to a clock's time is guaranteed to execute in a precise way.

Therefore there is ideally one single CPU clock for all the timers and then they are executed in sequence.

See a quote from W3C Timers Specification:

This API does not guarantee that timers will fire exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.

It does however guarantees an order of « does this timer should execute based on elapsed time since last tick call ? » based on when they were registered.

In classic timer if we have a setInterval of 0ms it will fill the event loop timer queue with callbacks (like A LOT) and if we have another of 1000ms interval it will be executed only after many of the 0ms callbacks are executed. This is not the case with ClockTimer, as it loops through all timers and checks if they should be executed there are more chance that the 1000ms callback will be executed in time.

You can also call .tick() manually to check all the timers at once on a specific important time.

Other cool stuff is that you manage all your timers in one place and therefore you can clear all of them at once. This is useful for example when you want to clear all timers when a game is over. Or when using those is irrelevant.

API

Clock

  • setInterval(handler, time, ...args) -> Delayed
  • setTimeout(handler, time, ...args) -> Delayed
  • duration(ms: number) -> Promise<void> - Convenience method to wait for a duration in async functions or promises. See associated JSdoc for more details.
  • clear() - clear all intervals and timeouts, and throw any promise created with duration.

Delayed

  • clear() -> void - Clear timeout/interval
  • reset() -> void - Reset elapsed time
  • active -> Boolean - Is it still active?
  • pause() -> void - Pause the execution
  • resume() -> void - Continue the execution
  • paused -> Boolean - Is is paused?

License

MIT

timer's People

Contributors

endel avatar greenkeeper[bot] avatar renatopp avatar screamz avatar zielak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

timer's Issues

TypeError: ClockTimer is not a constructor

I'm trying to get the tic-tac-toe sample colyseus game up and running on my machine, and I'm getting this error when I attempt to connect to the game. Here is the top of the TicTacToe.js file which is throwing the error:

var Room = require('colyseus').Room
  , ClockTimer = require('clock-timer.js')

const PATCH_RATE = 20
    , TURN_TIMEOUT = 10

class TicTacToe extends Room {

  constructor (options) {
    // call 'update' method each 50ms
    super(options, 1000 / PATCH_RATE)

    this.setState({
      currentTurn: null,
      players: {},
      board: [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
      winner: null,
      draw: null
    })

    this.clock = new ClockTimer(true)
  }

and here is the stack trace:

TypeError: ClockTimer is not a constructor
    at new TicTacToe (/home/daniel/javascript/test/server/rooms/tictactoe.js:21:18)
    at MatchMaker.create (/home/daniel/javascript/test/server/node_modules/colyseus/lib/match_maker.js:85:12)
    at MatchMaker.joinOrCreateByName (/home/daniel/javascript/test/server/node_modules/colyseus/lib/match_maker.js:48:75)
    at Server.onJoinRoomRequest (/home/daniel/javascript/test/server/node_modules/colyseus/lib/server.js:102:30)
    at Server.onMessage (/home/daniel/javascript/test/server/node_modules/colyseus/lib/server.js:77:14)
    at emitTwo (events.js:125:13)
    at WebSocket.emit (events.js:213:7)
    at Receiver.onbinary (/home/daniel/javascript/test/server/node_modules/colyseus/node_modules/ws/lib/WebSocket.js:848:10)
    at /home/daniel/javascript/test/server/node_modules/colyseus/node_modules/ws/lib/Receiver.js:628:18
    at /home/daniel/javascript/test/server/node_modules/colyseus/node_modules/ws/lib/Receiver.js:368:7

Help is greatly appreciated

An in-range update of typescript is breaking the build 🚨

Version 2.2.1 of typescript just got published.

Branch Build failing 🚨
Dependency typescript
Current Version 2.2.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As typescript is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪


Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details
Release Notes TypeScript 2.2

For release notes, check out the release announcement

For new features, check out the What's new in TypeScript 2.2.

For breaking changes, check out the Breaking changes in TypeScript 2.2 page.

For the complete list of fixed issues, check out the issues fixed in Typescript 2.2 RC and after Typescript 2.2 RC.

Download:

Special thanks to all contributors to this release:

  • Alexander Rusakov
  • Anatoly Ressin
  • Andreas Martin
  • Andrew Ochsner
  • Basarat Ali Syed
  • Dahan Gong
  • Dan Corder
  • David Sheldrick
  • @falsandtru
  • @flowmemo
  • Herrington Darkholme
  • Homa Wong
  • Joel Day
  • Kagami Sascha Rosylight
  • Klaus Meinhardt
  • Kārlis Gaņģis
  • Manish Giri
  • Masahiro Wakame
  • Raj Dosanjh
  • Slawomir Sadziak
  • Tingan Ho
  • Yuichi Nukiyama
Commits

The new version differs by 218 commits .

  • a29e8cf Update LKG
  • 1120971 Fix #14136: Make Object.create return any all the time
  • 6b5c448 Merge pull request #14131 from Microsoft/release-2.2_default_import_name
  • 125a8fa Merge pull request #14133 from aozgaa/MissingPropertyFix-2.2
  • b62b467 add periods
  • f2770a1 widen type, index signature, and add tests
  • a4cf12e cleanup
  • d9e0fff use getBaseTypeOfLiteralType
  • 150e2fb add tests
  • f133a67 wip testing
  • 2187e67 Get Widened Type
  • 533262c wip
  • ee13f31 Handle undefined import name
  • 510b384 Update LKG
  • 08fe20e [release-2.2] use separate process to probe if drive is safe to watch (#14098) (#14124)

There are 218 commits in total. See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Just to be sure to understand

Hi,

I'm exploring the Colyseus codebase, just to be sure to understand.

This library's purpose is to limit the amount of native setInterval inside the Server code and have something that calls all callbacks that would have been in a wild setInterval inside the same interval.

This way the tick is called on setInterval basis (optimally one setInterval within the whole server code, but in colyseus its in patch rate or simulation interval -> the fastest that occurs).

Also if we want to optimize, we can call tick method whenever we want to check if some interval can be played within the same event loop tick ? Is it?

If I understand correctly, that's DAMN smart. Good job !

An in-range update of clock.js is breaking the build 🚨

Version 1.1.6 of clock.js just got published.

Branch Build failing 🚨
Dependency clock.js
Current Version 1.1.5
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

clock.js is a direct dependency of this project this is very likely breaking your project right now. If other packages depend on you it’s very likely also breaking them.
I recommend you give this issue a very high priority. I’m sure you can resolve this 💪

Status Details - ❌ **continuous-integration/travis-ci/push** The Travis CI build could not complete due to an error [Details](https://travis-ci.org/gamestdio/clock-timer.js/builds/224956120)

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of rimraf is breaking the build 🚨

Version 2.6.0 of rimraf just got published.

Branch Build failing 🚨
Dependency rimraf
Current Version 2.5.4
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As rimraf is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪


Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details
Commits

The new version differs by 5 commits .

  • 5b661e4 v2.6.0
  • c09915f update tap
  • d53235d Make rimraf.sync 10000% more reliable on Windows
  • e8b10a7 Retry on EBUSY et al on non-windows platforms as well
  • 0fac5f7 Add --no-glob option to cli

See the full diff.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of typescript is breaking the build 🚨

Version 2.3.2 of typescript just got published.

Branch Build failing 🚨
Dependency typescript
Current Version 2.3.1
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As typescript is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪

Status Details - ❌ **continuous-integration/travis-ci/push** The Travis CI build failed [Details](https://travis-ci.org/gamestdio/clock-timer.js/builds/227005272?utm_source=github_status&utm_medium=notification)

Release Notes TypeScript 2.3.2

This release includes a fix to an inadvertent API breaking change affecting WebStorm & Intellij IDEA released part of TypeScript 2.3.1.

Download:

Commits

The new version differs by 4 commits0.

  • d1a202d Update LKG
  • a28c533 Update version
  • 9eaddb4 Merge pull request #15445 from RyanCavanaugh/sessionBackCompat
  • 9ce6b35 Add compat overload

false

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of typescript is breaking the build 🚨

Version 2.3.1 of typescript just got published.

Branch Build failing 🚨
Dependency typescript
Current Version 2.3.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As typescript is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪

Status Details - ❌ **continuous-integration/travis-ci/push** The Travis CI build failed [Details](https://travis-ci.org/gamestdio/clock-timer.js/builds/226551076)

Release Notes TypeScript 2.3

For release notes, check out the release announcement

For new features, check out the What's new in TypeScript 2.3.

For breaking changes, check out the Breaking changes in TypeScript 2.3 page.

For the complete list of fixed issues, check out the issues fixed in TypeScript 2.3 RC and after TypeScript 2.3 RC.

Download:

Special thanks to all contributors to this release:

  • Akinmade Bond
  • Anders Hejlsberg
  • Andy Hanson
  • Argelius Andreas
  • @arjunyel
  • Artem Roshko
  • Arthur Ozga
  • Bill Ticehurst
  • Christian Silver
  • Christophe Vidal
  • @cedvdb
  • Daniel Lehenbauer
  • Daniel Rosenwasser
  • Diullei Gomes
  • @e-cloud
  • Erik McClenney
  • @falsandtru
  • Hendrik Liebau
  • Herrington Darkholme
  • Igor Novozhilov
  • James Henry
  • Jason Jarrett
  • Jason Ramsay
  • Josh Goldberg
  • K. Preißer
  • Kagami Sascha Rosylight
  • Kanchalai Tanglertsampan
  • Klaus Meinhardt
  • Logan Mzz
  • Magnus Hiie
  • Matt Bierner
  • Matt McCutchen
  • Mike Busyrev
  • Mine Starks
  • Mohamed Hegazy
  • Natalie Coley
  • Nathan Shively-Sanders
  • Nico Kemnitz
  • Nicolas Henry
  • Oleg Mihailik
  • Ron Buckton
  • Ryan Cavanaugh
  • Soo Jae Hwang
  • Tuure Savuoja
  • Vadi Taslim
  • Vincent Bel
  • Vladimir Matveev
  • Zhengbo Li
Commits

The new version differs by 346 commits0.

  • 47e5569 Update LKG
  • 9ada915 Merge pull request #15381 from Microsoft/revert15104
  • fe0a307 Revert "Treat callback parameters as strictly covariant"
  • 96a3c91 Revert "Fix callback types to match covariantly"
  • 70bb2d3 Revert "Accept new baselines"
  • 3abd0c8 Revert "Add tests"
  • 42d6a9c Revert "Check callback return values bi-variantly"
  • d581bed Revert "Accept new baselines"
  • cf17be2 Revert "Add another test case"
  • e86512e Revert "Allow callbacks unioned with null and/or undefined"
  • 22647bb Revert "Update tests"
  • 8a85f4a Update LKG
  • 3c3b73e Merge branch 'master' into release-2.3
  • a0abadb Merge pull request #15320 from Microsoft/fixTypePredicateThisParameter
  • 5783435 Merge pull request #15330 from gcnew/exportConsts

There are 250 commits in total.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Performance improvement test

Hi @endel ,

I'm using your wonderful library in a project of mine based on state synchronization for an escape room in Montpellier, France.

I'm happy with it but i was asking myself what if we use a Set instead of a plain array ? Could this improve performances ?

delayedList.splice(i, 1);

delayed: Delayed[] = [];

Here some benchmarks

https://www.geeksforgeeks.org/set-vs-array-in-javascript/
https://stackoverflow.com/a/39010462/5320409

What do you think ? Changes would be minor

An in-range update of mocha is breaking the build 🚨

Version 3.3.0 of mocha just got published.

Branch Build failing 🚨
Dependency mocha
Current Version 3.2.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As mocha is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪

Status Details - ❌ **continuous-integration/travis-ci/push** The Travis CI build failed [Details](https://travis-ci.org/gamestdio/clock-timer.js/builds/225145588)

Release Notes coverave

Thanks to all our contributors, maintainers, sponsors, and users! ❤️

As highlights:

  • We've got coverage now!
  • Testing is looking less flaky \o/.
  • No more nitpicking about "mocha.js" build on PRs.

🎉 Enhancements

  • #2659: Adds support for loading reporter from an absolute or relative path (@sul4bh)
  • #2769: Support --inspect-brk on command-line (@igwejk)

🐛 Fixes

  • #2662: Replace unicode chars w/ hex codes in HTML reporter (@rotemdan)

🔍 Coverage

🔩 Other

Commits

The new version differs by 89 commits0.

  • fb1687e :ship: Release v3.3.0
  • 1943e02 Add Changelog for v3.3.0
  • 861e968 Refactor literal play-icon hex code to a var
  • 1d3c5bc Fix typo in karma.conf.js
  • 9bd9389 Fix spec paths in test HTML files
  • 0a93024 Adds tests for loading reporters w/ relative/absolute paths (#2773)
  • 73929ad Comment special treatment of '+' in URL query parsing
  • e2c9514 Merge pull request #2769 from igwejk/support_inspect_break_in_opts
  • 038c636 Support --inspect-brk on command-line
  • b4ebabd Merge pull request #2727 from lamby/reproducible-build
  • 882347b Please make the build reproducible.
  • a2fc76c Merge pull request #2703 from seppevs/cover_utils_some_fn_with_tests
  • ed61cd0 cover .some() function in utils.js with tests
  • f42cbf4 Merge pull request #2701 from craigtaub/landingSpec
  • 6065242 use stubbed symbol

There are 89 commits in total.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Calling clock.clear() inside a callback function breaks the tick

When you try to clear the clock inside a timeout or interval callback, the tick function fail:

TypeError: Cannot read property 'active' of undefined

Reproducing it:

const clock = new ClockTimer();

clock.setTimeout(() => {}, 0);
clock.setTimeout(() => {
  clock.clear();
}, 0);
clock.setTimeout(() => {}, 0);

clock.tick();

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Adding promise syntax

Hello @endel

I've made some test improving the library this way:

export class Clock extends BaseClock {
  /**
   * Return a promise that resolves after the duration
   * @param duration in ms
   * @returns
   * TODO: Add some mecanism to avoid dead promise if time get destructed
   */
  duration = (duration: number) => new Promise((resolve) => this.setTimeout(resolve, duration));
}

This works well and allow to use the syntax

await clock.duration(10000)
console.log("Hello");

The issue might rise when the Clock.clear method is invoked as the timer get never removed and therefore the promise never resolves. This results in a memory leak? While its edge-case.

As far as i can see this could be solved by overriding the clear function to send an abort signal like resolving the promise with {"cancelled": true} and therefore in the duration function make a no-op.

Why would i need a await syntax ? Because I'm chaining animations for a real-life experience (escape room) and I want to be able to avoid callback hell.

like writing this code

async function walkStepsEffect({ setDeviceState, clock }: Controls) {
  setDeviceState({ stepperState: StepperState.One });
  await clock.duration(250);
  setDeviceState({ stepperState: StepperState.Two });
  await clock.duration(250);
  setDeviceState({ stepperState: StepperState.Three });
  await clock.duration(250);
  setDeviceState({ stepperState: StepperState.Done });
}

Do you have any other ideas? I can work on a pull request.

An in-range update of ts-node is breaking the build 🚨

The devDependency ts-node was updated from 8.1.1 to 8.2.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

ts-node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for Cache FS Operations

Added

  • Expand FS cache to all file system operations

Changed

  • Pass all files to "root scripts" TypeScript compiler option to improve performance
Commits

The new version differs by 3 commits.

  • b8fd523 8.2.0
  • 1e838f7 Caching all FS operations improves perf 1.25x
  • 6dad5ad List all files in memory cache improves perf 1.4x

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.