function wait to execute

138 Views Asked by At

In Matlab functions can be started at events,but occasionally, like with the resize function, the events are called in rapid order and the function is called many times in succession, which can cause weird behavior and lag. Is there a way to have it listen for the event but only execute on the last event in a time range, e.g. .5 second?

I tried using a persistent variable that each one would update and it would only run if the variable still equaled what they set it to after .5 seconds, but this didn't work. Are there any clean ways to do this in Matlab or any language that I can steal ideas from?

edit: For example here is an implementation of the persistent variable method that I tried:

function practice
a = uipanel('ResizeFcn',@Delay,'Units','Normalized');
uicontrol(a)
end

function Delay(s,cb)
persistent a
if isempty(a)
    a = 0;
end
a = a+1;
b = a;
pause(.1);
if b~=a
    %disp(a-b)
else
    %do work here
end
end

This method doesn't seem to work all the time, but that might just be because of the use of the magic number in pause(). It is also very unclear as to what it does without deep reading.

1

There are 1 best solutions below

2
On BEST ANSWER

The "weird behavior and lag" you see is almost always a result of callbacks interrupting each other's execution, and repeated unnecessary executions of the same callbacks piling up.

To avoid this, you can typically set the Interruptible property of the control/component to 'off' instead of the default 'on', and set the BusyAction property to 'cancel' instead of the default 'queue'.

That won't solve all such issues (for example, you might have a callback that needs to respond to a live data feed that is just running too fast to keep up with), but for many situations it's the right approach. In particular for the situation of a ResizeFcn callback, it will mean that the callback will only be called if it's not already running, and so stops any piling up of callbacks, and any effects of the same function running twice at once.