     delay-nanos
     interval-nanos
     iteration-start-nanos
-    { stop? boolean }
+    quotation-running?
     thread ;
 
 <PRIVATE

    [ iteration-start-nanos>> - ] [ interval-nanos>> ] bi <
    [ set-next-alarm-time ] dip
    [ dup iteration-start-nanos>> ] [ 0 ] if
    sleep-until call-alarm-loop ;

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

: call-alarm-loop ( alarm -- )
    dup stop?>> [
        drop
    ] [
        [ quot>> call( -- ) ] keep
        maybe-loop-alarm
    ] if ;

: call-alarm ( alarm -- )
    '[
        _ self >>thread
        [ delay-nanos>> [ sleep ] when* ]
        [ nano-count >>iteration-start-nanos call-alarm-loop ] bi
    ] "Alarm execution" spawn drop ;

PRIVATE>


        swap >>quot ; inline

: start-alarm ( alarm -- )
    [
        '[
            _ nano-count >>start-nanos
            [ delay-nanos>> [ sleep ] when* ]
            [ nano-count >>iteration-start-nanos call-alarm-loop ] bi
        ] "Alarm execution" spawn
    ] keep thread<< ;

: stop-alarm ( alarm -- )
    dup quotation-running?>> [
        f >>thread drop
    ] [
        [ [ interrupt ] when* f ] change-thread drop
    ] if ;

<PRIVATE

