Skip to main content
Module

x/async_channels/mod.ts>time.Timer

Inspired by Go & Clojure Channels, async_channels provides channels as an asynchronous communication method between asynchronous functions.
Latest
class time.Timer
import { time } from "https://deno.land/x/async_channels@v1.0.0-rc8/mod.ts";
const { Timer } = time;

Constructors

new
Timer(duration: number, options?: ChannelOptions)

Properties

protected
ctrl: AbortController
protected
timeoutId: number
readonly
c: Receiver<Date>

Methods

reset(duration: number): boolean

reset changes the timer to expire after duration. It returns true if the timer had been active, false if the timer had expired or been stopped.

reset should be invoked only on stopped or expired timers with drained channels.

If a program has already received a value from t.c, the timer is known to have expired and the channel drained, so t.reset() can be used directly. If a program has not yet received a value from t.c, however, the timer must be stopped and—if stop reports that the timer expired before being stopped—the channel explicitly drained:

if (!t.stop()) {
  await t.c.get()
}
t.reset(d)

This should not be done concurrent to other receives from the Timer's channel.

Note that it is not possible to use reset's return value correctly, as there is a race condition between draining the channel and the new timer expiring. reset should always be invoked on stopped or expired channels, as described above. The return value exists to preserve compatibility with existing programs.

stop(): boolean

stop prevents the Timer from firing. It returns true if the call stops the timer, false if the timer has already expired or been stopped. stop does not close the channel, to prevent a read from the channel succeeding incorrectly.

To ensure the channel is empty after a call to stop, check the return value and drain the channel. For example, assuming the program has not received from t.C already:

if (!t.stop()) {
  await t.c.get()
}

This cannot be done concurrent to other receives from the Timer's channel or other calls to the Timer's stop method.

For a timer created with AfterFunc(d, f), if t.stop returns false, then the timer has already expired and the function f has been started in its own goroutine; stop does not wait for f to complete before returning. If the caller needs to know whether f is completed, it must coordinate with f explicitly.