 
         @context.events.reset_frame_events()
 
+    set_timeout: (timeout, reset=true)=>
+        'WARNING: Timeout set: ' + timeout
+        @timeout = timeout
+        if reset then @reset_timeout()
+
     reset_timeout: =>
-        @timeout_timer = 0
-        @enabled = @enabled or @run()
+        if not @enabled
+            console.log 'Main loop running: ' + Math.floor( performance.now())
+
+        @timeout_timer =  @timeout
+        @enabled = true
 
 
 module.exports = {MainLoop}

        @frame_duration = 16
        @last_frame_durations = [16, 16, 16, 16, 16, 16, 16, 16, 16, 16]
        @_fdi = 0
        @last_time = 0
        @timeout = null
        @timeout_timer = null
        @enabled = false
        @context = context
        @timeout = context.MYOU_PARAMS.timeout
        @timeout? and console.log 'WARNING: Timeout set: ' + @timeout

    run: ->
        @_bound_tick = @tick.bind @
        requestAnimationFrame @_bound_tick
        not @enabled and @timeout? and console.log 'Main loop running: ' + Math.floor(performance.now())
        @enabled = true
        @last_time = performance.now()


    stop: ->
        cancelAnimationFrame @_bound_tick
        @enabled = false

    tick: ->
        requestAnimationFrame @_bound_tick
        time = performance.now()
        @frame_duration = frame_duration = Math.min time - @last_time, MAX_FRAME_DURATION


        if @timeout? and @timeout_timer > @timeout
            @stop()
            @timeout_timer = 0
            console.log 'Main loop paused: ' + Math.floor(time)

        if @enabled == false or @context.loaded_scenes.length == 0
            return

        @timeout_timer += frame_duration
        @last_frame_durations[@_fdi] = frame_duration
        @_fdi = (@_fdi+1) % @last_frame_durations.length

        @last_time = time

        for scene in @context.loaded_scenes
            if not scene.enabled

{get_last_char_phy, step_world, step_world, phy_to_ob} = require './physics'
# Logic assumes a frame won't be longer than this
# Below that point, things go slow motion
MAX_FRAME_DURATION = 167  # 6 fps

class MainLoop

