# Use mouse in different routines causes a long delay

**URL:** <https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251>\
**Category:** Builder\
**Tags:** timing\
**Created:** [January 10, 2019, 6:50pm UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251 "2019-01-10T18:50:12Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![Valeria\_Gonzalez](https://avatars.discourse-cdn.com/v4/letter/v/f14d63/32.png) [@Valeria\_Gonzalez](https://discourse.psychopy.org/u/Valeria_Gonzalez)\
**Post date:** [January 10, 2019, 6:50pm UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/1 "2019-01-10T18:50:13Z")

</div>

\*\*Win10:  
**PsychoPy version** (e.g. 1.85.4):

Hi! I’m working in a program for an experiment about choice (in pigeons). The animal has forced and choice trials. In a choice trial the animal can choose between two alternatives -A and B- (one ‘click’), if the animal choose A, two different images can appear (one each trial) for 30s (images have a different probability of occurrence and a different probability of reinforcement). The same is true for alternative B.  
Because what happen is conditional to the initial choice, I attached an excel file with all the conditions. So, I have 4 routines after the choice routine (one per image).

 ![50](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/3X/1/f/1fcc67485beaf8036ab26d2ebee9fe52865189cf.png)

Depending of the choice and the probability, the program skip the other routines. For instance: if the animal chooses B, and it’s selected S4 (routine in the picture), the program skip Splus, Sminus, and S3 routines. So far so good.

I need to record all the pecks of the animal during the images (‘clicking’ for the program). The code added to that works just fine. The problem is that, when I added a mouse in each routine (Splus, Sminus, S3 and S4) there is a long delay (around 10s) between the presentation of routine S3 or S4 and the next routine (foodreward). It does not happen if the image (and therefore routine) presented is Splus or Sminus.

I though it was the code to register clicks, but when I remove it, I still have the delay. But for instance, if I remove the mouse in S3, the delay after S3 and foodreward disappeares.

I don’t know how to fix it ☹

---

<div class="post-metadata">

**Author:** ![Michael](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.psychopy.org/michael/32/16_2.png) [@Michael](https://discourse.psychopy.org/u/Michael)\
**Post date:** [January 10, 2019, 11:21pm UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/2 "2019-01-10T23:21:52Z")

</div>

Well done, it seems like you have most of your trial procedure implemented. To find the cause of this unexpected delay, though, we’ll probably need to see your Builder `.psyexp` file, to be able to see the settings of your various mouse components and the effects of the custom code.

---

<div class="post-metadata">

**Author:** ![Valeria\_Gonzalez](https://avatars.discourse-cdn.com/v4/letter/v/f14d63/32.png) [@Valeria\_Gonzalez](https://discourse.psychopy.org/u/Valeria_Gonzalez)\
**Post date:** [January 11, 2019, 6:56pm UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/3 "2019-01-11T18:56:50Z")

</div>

[blockSelection.xlsx](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/2X/e/e14b1a6eca7d51730e50c90cac8b0de54f3c6959.xlsx) (8.4 KB)  
 ![CH](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/3X/8/d/8df415e00a082435a6feda865fce402db0910f53.png) ![IL1](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/3X/6/f/6f1c54439372d4acf617c8dbbf42a605c2e23c52.png) ![IL2](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/3X/2/1/21910be8c2049050d30b754169e86226d85ebf38.png) ![RH](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/3X/2/6/265221602521569ed03fdfe8033acf241bc60da1.png) [sub\_opt\_choice.xlsx](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/2X/8/82d45ae3cad176630ffb6e36ae699f66eb158281.xlsx) (9.5 KB)  
[sub\_opt\_TEST.psyexp](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/2X/c/c8363ed068c7207db785e4e9048fa1ea8fc377ac.psyexp) (101.1 KB)  
 ![SV](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/3X/0/2/02162586f16f3cb9e10e0b171a0f2ab0e43dcbaf.png) [tl1.xlsx](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/2X/3/3f69700f18b08c84bcdeb242934cfd0329812197.xlsx) (9.9 KB)  
 ![TV](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/3X/8/8/88a9b301e8c7fa43b01fd63840dd051cab1c4915.png)

---

<div class="post-metadata">

**Author:** ![Michael](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.psychopy.org/michael/32/16_2.png) [@Michael](https://discourse.psychopy.org/u/Michael)\
**Post date:** [January 13, 2019, 9:04pm UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/4 "2019-01-13T21:04:52Z")

</div>

Hi,

Sorry for the long delay. From only a quick look at your code, I can’t pretend to understand all of the logic, but would make a recommendation that you remove anything like this from your code components:

```auto
while mouseS3.isPressedIn(S3_) and not (mouseS3.isPressedIn(background_5)):
        continue

```

In general Python programming terms, a tight loop like this will completely consume your CPU, strangling any other processes. This can cause unexpected delays as other processes (outside PsychoPy) finally jump in and wrest control of the CPU from you. The normal Builder drawing loop (of effectively pausing for a few milliseconds on every screen refresh) allows PsychoPy to be a good citizen and give other processes some access to the CPU.

So the consequences of these sorts of loop are two-fold:

- you cause bottlenecks for other programs, which can then cause poor performance as they try to compete.
- you’re also stopping Builder’s natural drawing cycle. If the conditions of your test aren’t met for a while, your effectively pausing all drawing and anything else other than this specific check for mouse presses. This means everything else that Builder normally intends to do on a frequenct cycle (checking the keyboard, redrawing the screen, checking the onset and offset time of stimuli, and so on, is being put on ice.

As a general rule, avoid putting any indefinite loops or pauses in Builder code components, as they disrupt Builder’s inherent event/draw loop cycle.

But I guess that loop is there for some reason, so you need to restructure your code to achieve the same result. Again, I’m not too sure of the required logic here, so can’t give specific advice.

---

<div class="post-metadata">

**Author:** ![Valeria\_Gonzalez](https://avatars.discourse-cdn.com/v4/letter/v/f14d63/32.png) [@Valeria\_Gonzalez](https://discourse.psychopy.org/u/Valeria_Gonzalez)\
**Post date:** [January 14, 2019, 5:05am UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/5 "2019-01-14T05:05:05Z")

</div>

Hi Michael!  
Thank you for the advice! But the problem persist even when I remove all the response-related code (I was of course just testing but I actually need to record data). So, I don’t know what the problem can be.

---

<div class="post-metadata">

**Author:** ![Michael](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.psychopy.org/michael/32/16_2.png) [@Michael](https://discourse.psychopy.org/u/Michael)\
**Post date:** [January 14, 2019, 11:38pm UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/6 "2019-01-14T23:38:27Z")

</div>

I’m still a bit puzzled by this myself, and just realised that I don’t really understand how Builder decides when a component is finished even in normal circumstances. Some points that are unlikely related to your issues, but anyway:

- I love looking at other people’s experiments and finding a routine called `Put_bird_in_box`.
- You define circle stimuli with 999999 vertices. Nothing comes for free: these stimuli with nearly a million points are massive overkill in terms of memory required, to achieve no real advantage (i.e. the pixels on your screen have a finite size. If a circle with 100 vertices still has visible corners, then bump it up to 200, say, rather than orders of magnitude more vertices than can physically be drawn on the pixel grid.
- I’m not sure why you call `thisExp.nextEntry()`. Calls to `nextEntry()` shouldn’t really be necessary in Builder code, as it is taking care of all of your loops and trials for you.

Those points above probably won’t fix anything related to this particular issue. So how about you post a version of your `.psyexp` file that works in every respect except for this mystery delay, but has had the (potentially) infinite loops removed from your code? That might help to narrow things down.

---

<div class="post-metadata">

**Author:** ![Valeria\_Gonzalez](https://avatars.discourse-cdn.com/v4/letter/v/f14d63/32.png) [@Valeria\_Gonzalez](https://discourse.psychopy.org/u/Valeria_Gonzalez)\
**Post date:** [January 15, 2019, 2:46pm UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/7 "2019-01-15T14:46:31Z")

</div>

Hi!  
I did a simpler version checking the number of vertices and deleting most of the saving data code. I even deleted the pictures. So far, the only thing that deletes the delay in the choice loop is when I delete the mouses.

[sub\_opt\_TEST2.psyexp](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/2X/9/953786dd7d80fa886f82029f1dcb8b5eaf2a34ed.psyexp) (80.2 KB)

-I call thisExp.Entry() because that is what is suggested in the basic manual ([psychopy.data - functions for storing/saving/analysing data — PsychoPy v2021.2](http://www.psychopy.org/api/data.html))-

EDIT: Here is a version with only choice trials. Still the same problem  
[sub\_opt\_TESTONLYCHOICE.psyexp](https://us1.discourse-cdn.com/flex002/uploads/psychopy/original/2X/f/f861e2d59f35d1015816613ee8eb14091d98e9ae.psyexp) (70.9 KB)

---

<div class="post-metadata">

**Author:** ![Michael](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.psychopy.org/michael/32/16_2.png) [@Michael](https://discourse.psychopy.org/u/Michael)\
**Post date:** [January 22, 2019, 8:53pm UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/8 "2019-01-22T20:53:33Z")

</div>

Hi Valeria, sorry for the delay, I’ve been on holiday.

Is this still a live issue? If so, I’ll look at your files above.

> [@Valeria\_Gonzalez](#):
>
> -I call thisExp.Entry() because that is what is suggested in the basic manual

That is oriented for people coding their own experiments from scratch (and even then, `nextEntry()` isn’t usually necessary). You shouldn’t need to make this call at all in a Builder-generated experiment (and it might even cause undesired side effects).

---

<div class="post-metadata">

**Author:** ![Valeria\_Gonzalez](https://avatars.discourse-cdn.com/v4/letter/v/f14d63/32.png) [@Valeria\_Gonzalez](https://discourse.psychopy.org/u/Valeria_Gonzalez)\
**Post date:** [January 22, 2019, 10:56pm UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/9 "2019-01-22T22:56:04Z")

</div>

Yes, still is! In the meantime I realized the delay is equivalent to the duration of all four routines. It does not make any sense to me what they seem to be ‘active’ even after the ‘skip routine’ instruction was on effect.

Thanks for the note on Exp.Entry()!

---

<div class="post-metadata">

**Author:** ![Michael](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.psychopy.org/michael/32/16_2.png) [@Michael](https://discourse.psychopy.org/u/Michael)\
**Post date:** [January 23, 2019, 8:55am UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/10 "2019-01-23T08:55:48Z")

</div>

> [@](#):
>
> I realized the delay is equivalent to the duration of all four routines

That observation makes all the difference. I’ve only just realised that you are using a very old PsychoPy release. The ability to use `continueRoutine = False` in the “begin routine” tab was only added about the time of that version, so you might not have that capacity.

> <https://github.com/psychopy/psychopy/issues/1143>
>
> To have conditional execution of a routine (e.g. a rest break every 10th trial),… a code snippet like this is often suggested:
> 
> \`\`\`
> if not loopName.thisN in \[9, 19, 29\]:
> continueRoutine = False
> \`\`\`
> 
> It would be logical if such code was placed in the "Begin routine" tab of a code component. But this is executed immediately prior to a routine:
> 
> \`\`\`
> \#-------Start Routine "trial"-------
> continueRoutine = True
> \`\`\`
> 
> So a change affecting \`continueRoutine\` in the "begin routine" tab is immediately counteracted by the template code. 
> 
> Should the above line in the compiled code be shifted to \_before\_ where any "begin routine" code is placed? Otherwise any attempt to end a routine has to occur in the "Every frame" tab. 
> 
> Needing to always put \`continueRoutine\` code in the "Every frame" tab has two disadvantages:
> \- Probably one frame of a routine will be presented before it can then be terminated. This could cause a visible flicker in stimuli, or some other undesired action.
> \- It encourages inappropriate mixing of logic, and needlessly performing a single check multiple times. That is, some \`continueRoutine\` checks should be evaluated only once, prior to a routine (e.g. checking a trial number), while other \`continueRoutine\` checks should be monitored continuously, on every frame. We should allow hose checks to be placed where they should be, logically and performance-wise.

Can you push the “compile script” button in the toolbar and search for the line:

```
# ------Prepare to start Routine "S_plus"-------

```

and paste in a message here everything between that line and this one:

```
# -------Start Routine "S_plus"-------

```

This wouldn’t explain why the code did work before, but eliminating this possibility would be useful. If it isn’t the problem, then we need to debug elsewhere.

Lastly, that “each frame” code still includes lines like this in multiple places:

```auto
while (mouseA.isPressedIn(sub_area)):
        continue

```

I think as discussed above, this sort of code really needs to be deleted, as it will interfere with Builder’s timing. If it serves a particular function, please describe it, and we can discuss how to implement it without holding up Builder’s drawing cycle.

---

<div class="post-metadata">

**Author:** ![Valeria\_Gonzalez](https://avatars.discourse-cdn.com/v4/letter/v/f14d63/32.png) [@Valeria\_Gonzalez](https://discourse.psychopy.org/u/Valeria_Gonzalez)\
**Post date:** [January 30, 2019, 3:24am UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/11 "2019-01-30T03:24:11Z")

</div>

I’m so sorry for the delay. For some reason this time I did not get an email with your answer.

Here it is the code

```auto

# ------Prepare to start Routine "S_plus"-------
    t = 0
    S_plusClock.reset() # clock
    frameN = -1
    continueRoutine = True
    routineTimer.add(3.000000)
    # update component parameters for each repeat
    Splus.setPos(sublocation)
    if skip_S_plus:
        continueRoutine = False
    # setup some python lists for storing info about the mouseA_5
    # keep track of which components have finished
    S_plusComponents = [Splus, background_3, mouseA_5]
    for thisComponent in S_plusComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    
    # -------Start Routine "S_plus"-------

```

Also, I am using a touch screen (the pigeon peck the pictures). So, If I don’t use:

> while (mouseA.isPressedIn(sub\_area)):  
> continue

then It registers as different pecks a long press to the touchscreen. That’s what I found online to avoid that problem; but if you have a better solution I would love to implement it.

Again, I apologize for my delay.  
Thank you for your help!

---

<div class="post-metadata">

**Author:** ![Michael](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.psychopy.org/michael/32/16_2.png) [@Michael](https://discourse.psychopy.org/u/Michael)\
**Post date:** [January 30, 2019, 5:30am UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/12 "2019-01-30T05:30:24Z")

</div>

Hi,

Your code shows that you are using a version which should respond to `continueRoutine` properly (but I think you’ve mentioned that it sometimes works OK anyway, so that was maybe a blind alley).

However, it would still be worth updating to the latest version of PsychoPy: the mouse component has changed to allow the detection of mouse presses in certain stimuli (i.e. it now has a field called “clickable stimuli”, where you just list the names of the stimuli that are valid click targets). This means that you can allow PsychoPy to do some of the hard work for you. It also seems to handle responding just once to a mouse click. i.e. using the latest version of PsychoPy, the code that gets generated from your .psyexp file probably looks different to me than it does for you.

I’m still concerned about the lines like:

```auto
while (mouseA.isPressedIn(sub_area)):
        continue

```

They could conceivably allow the routine to last beyond the specified 3 seconds if the pigeon keeps pressing the target. But also, I’m not sure what it achieves. Your code should just trigger on the initial click, and then, by setting `continueRoutine` to `False`, it should immediately end. There should be no need to guard against any other detections, as this “every frame” code shouldn’t get the chance to run again on this trial. Or is it important to you to end the trial after the press is completed, rather than when it is initially detected?

So, some debugging: In the “End routine” tab of the code on the “Choice” routine, put something like:

```auto
print('### Trial: ' + str(Choice1.thisN))
# these print statements might need adjusting if you are using Python 2:
print('skip_S_plus: ', skip_S_plus)
print('skip_S_minus: ', skip_S_minus)
print('skip_S3: ', skip_S3)
print('skip_S4: ', skip_S4)

```

Do the results fit with what you expect?

If that doesn’t give any obvious hints, then you should do the same in you “each frame” code. i.e. insert some statements to allow you to check that the logic is being followed as you intend. Making print statements up to, say, 60 times a second can be burdensome though and lead to backlogs, so for code in that tab, you might find that sending messages to the experiment log might be more practical. See:

[https://www.psychopy.org/coder/codeLogging.html](https://www.psychopy.org/coder/codeLogging.html)

and make sure that your experiment settings are set to record the level of log messages you are generating.

---

<div class="post-metadata">

**Author:** ![Valeria\_Gonzalez](https://avatars.discourse-cdn.com/v4/letter/v/f14d63/32.png) [@Valeria\_Gonzalez](https://discourse.psychopy.org/u/Valeria_Gonzalez)\
**Post date:** [February 3, 2019, 9:23pm UTC](https://discourse.psychopy.org/t/use-mouse-in-different-routines-causes-a-long-delay/6251/13 "2019-02-03T21:23:07Z")

</div>

Hi!

It took me a while to update the task to the new version 3.0.3 and initially I had the same problem. But at the end, deleting the code and using just the alternative that the mouse component has now was enough to fix the problem.

I am not completely sure where the program was stuck, but It seems that those while loops to register clicks were slowing down the program.

Thank you so much for your help and patience!

Val
