【发布时间】:2014-02-21 09:20:21
【问题描述】:
我想编写一个类似于通常在 Javascript 中实现的 Debounce 程序。例如debounce function in Underscore.js。
我认为它可能看起来像这样:
procedure Debounce(const TimeMS : integer; MyAnonymousProcedure : TProc);
并且可以像这样使用:
begin
Debounce(200, procedure
begin
//Do something here...
end);
end;
可能的实施 #1
Debounce() 过程将检查自调用目标方法以来的时间。如果目标方法调用在 X 时间内被调用,则会延迟。
伪代码版本:
procedure Debounce(const TimeMS : integer; MyAnonymousProcedure : TProc);
var
TimeSinceCalled : integer;
begin
TimeSinceCalled := FindTimeSinceProcedureLastCalled(MyAnonymousProcedure);
if TimeMS < TimeSinceCalled then
begin
// The procedure hasn't been called recently,
SaveTimeOfProcedureCall(MyAnonymousProcedure); // so save the current time...
MyAnonymousProcedure; // ...and call the procedure.
end else
begin
// The procedure has been called recently so we use a timer
// to call the procedure in X milliseconds.
// The timer is reset each time Debounce() is called
// so procedures will only be called when the Debounce time-out has
// be passed.
GlobalTimer.Reset;
GlobalTimer.CallProcedureIn(MyAnonymousProcedure, TimeMS);
end;
end;
我面临的问题是我需要一些方法来识别目标过程。我的第一个想法是使用目标过程的方法地址作为ID。例如:ID := Address(Foo);ID := Addr(Foo);
但这不适用于匿名方法,因为它们在我的测试中使用相同的地址。理想情况下,ID 应该是自动生成的。有任何想法吗?
【问题讨论】: