Modal Timer Keeps Running Faster and Faster?

I’m creating a script that uses a modal timer, but I noticed that every time I call it, it goes faster with no way for me to reverse it. How would I reset it to the initial timer rate? It’s based on the default modal timer in the templates section, and I noticed that that script has the same issue. Is it because it keeps adding handlers, or another problem? Below is the problematic section of code. Any help would be appreciated!

_timer = None


def modal(self, context, event):
    global counter
    vis_run = context.scene.vis_run
    if event.type == 'TIMER':
        counter += 1
        print (counter)
        if not vis_run:
            vis_run = False
            return {"FINISHED"}
        else:
            if counter <= 25:
                bpy.data.node_groups["NodeGroup"].nodes["Mix"].inputs[7].default_value = (1,0,0,1)
                bpy.data.materials["Glow"].node_tree.nodes["Mix"].inputs[0].default_value = 0
            else:
                bpy.data.node_groups["NodeGroup"].nodes["Mix"].inputs[7].default_value = (.3,.3,.3,1)
                bpy.data.materials["Glow"].node_tree.nodes["Mix"].inputs[0].default_value = 1
        
    if counter == 35: 
        counter = 0
        

    return {'PASS_THROUGH'}

def execute(self, context):
    global tracker
    context.scene.vis_run = True
    wm = context.window_manager
    self._timer = wm.event_timer_add(0.01, window=context.window)
    wm.modal_handler_add(self)
    return {'RUNNING_MODAL'}

                

def cancel(self, context):
    wm = context.window_manager
    self._timer = None
    wm.event_timer_remove(self._timer)

every time you call it you’re creating another timer, which is running in parallel to the first one, so now instead of adding 1 every time the timer fires, you’re adding 2. when you call it a third time you’re adding 3, repeat ad nauseum.

if not vis_run:
    vis_run = False
    return {"FINISHED"}

methinks you meant to check if vis_run, not if not vis_run.

1 Like