module Haste.Timer (Timer, Interval (..), setTimer, stopTimer) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Monad.IO.Class
import Haste.Foreign
import Haste.Events.Core
type Identifier = Int
data Timer = Timer !Identifier !Interval
data Interval
= Once !Int
| Repeat !Int
setTimer :: MonadEvent m
=> Interval
-> m ()
-> m Timer
setTimer i f = do
f' <- mkHandler $ const f
liftIO $ do
flip Timer i <$> case i of
Once n -> timeout n (f' ())
Repeat n -> interval n (f' ())
timeout :: Int -> IO () -> IO Int
timeout = ffi "(function(t,f){window.setTimeout(f,t);})"
interval :: Int -> IO () -> IO Int
interval = ffi "(function(t,f){window.setInterval(f,t);})"
stopTimer :: MonadIO m => Timer -> m ()
stopTimer (Timer ident (Once _)) = liftIO $ clearTimeout ident
stopTimer (Timer ident (Repeat _)) = liftIO $ clearInterval ident
clearTimeout :: Int -> IO ()
clearTimeout = ffi "(function(id){window.clearTimeout(id);})"
clearInterval :: Int -> IO ()
clearInterval = ffi "(function(id){window.clearInterval(id);})"