         maybe-loop-timer
     ] if ;
 
-: sleep-delay ( timer -- )
+TYPED: sleep-delay ( timer: timer -- )
     dup stop-timer? [
         drop
     ] [

    over delay-nanos>> [ + ] when*
    >>iteration-start-nanos ;

: stop-timer? ( timer -- ? )
    { [ thread>> self eq? not ] [ restart?>> ] } 1|| ;

DEFER: call-timer-loop

: loop-timer ( timer -- )
    nano-count over
    [ iteration-start-nanos>> - ] [ interval-nanos>> ] bi <
    [ set-next-timer-time ] dip
    [ dup iteration-start-nanos>> ] [ 0 ] if
    0 or sleep-until call-timer-loop ;

: maybe-loop-timer ( timer -- )
    dup { [ stop-timer? ] [ interval-nanos>> not ] } 1||
    [ drop ] [ loop-timer ] if ;

: call-timer-loop ( timer -- )
    dup stop-timer? [
        drop
    ] [

M: real >nanoseconds >integer ;
M: duration >nanoseconds duration>nanoseconds >integer ;

TYPED: set-next-timer-time ( timer: timer -- timer )
    ! start + delay + ceiling((now - (start + delay)) / interval) * interval
    nano-count
    over start-nanos>> -
    over delay-nanos>> [ - ] when*
    over interval-nanos>> / ceiling
