每个Haxe开发人员都知道,您可以使用haxe.Timer.delayed()将函数调用延迟一段时间。但是这个函数对于Neko来说根本不存在。有没有办法达到同样的效果?
发布于 2008-10-22 16:06:20
我得先检查一下,但是
function delayed(f, time) {
neko.vm.Thread.create(function() {
neko.Sys.sleep(time);
f();
});
}可能是最接近的东西了。唯一的缺点是应用程序变得多线程,这可能会导致严重的问题。
发布于 2010-05-19 05:05:12
我考虑过你的问题,我认为最好的方法是为Neko创建你自己的Timer类。我为你做了一个计时器类:
NekoTimer.hx
package;
import neko.Sys;
class NekoTimer
{
private static var threadActive:Bool = false;
private static var timersList:Array<TimerInfo> = new Array<TimerInfo>();
private static var timerInterval:Float = 0.1;
public static function addTimer(interval:Int, callMethod:Void->Void):Int
{
//setup timer thread if not yet active
if (!threadActive) setupTimerThread();
//add the given timer
return timersList.push(new TimerInfo(interval, callMethod, Sys.time() * 1000)) - 1;
}
public static function delTimer(id:Int):Void
{
timersList.splice(id, 1);
}
private static function setupTimerThread():Void
{
threadActive = true;
neko.vm.Thread.create(function() {
while (true) {
Sys.sleep(timerInterval);
for (timer in timersList) {
if (Sys.time() * 1000 - timer.lastCallTimestamp >= timer.interval) {
timer.callMethod();
timer.lastCallTimestamp = Sys.time() * 1000;
}
}
}
});
}
}
private class TimerInfo
{
public var interval:Int;
public var callMethod:Void->Void;
public var lastCallTimestamp:Float;
public function new(interval:Int, callMethod:Void->Void, lastCallTimestamp:Float) {
this.interval = interval;
this.callMethod = callMethod;
this.lastCallTimestamp = lastCallTimestamp;
}
}这样叫它:
package ;
import neko.Lib;
class Main
{
private var timerId:Int;
public function new()
{
trace("setting up timer...");
timerId = NekoTimer.addTimer(5000, timerCallback);
trace(timerId);
//idle main app
while (true) { }
}
private function timerCallback():Void
{
trace("it's now 5 seconds later");
NekoTimer.delTimer(timerId);
trace("removed timer");
}
//neko constructor
static function main()
{
new Main();
}
}希望这能有所帮助。
注:这一次的准确度为100ms。您可以通过减小timerInterval设置来增加此设置。
发布于 2013-12-20 01:37:26
我也使用了这个类,我发现了一个问题。因为不是完全实时的,所以它休眠间隔,调用函数,然后再次休眠间隔。因此,根据运行函数的时间长短,它会变得更慢或更快。
我已经解决了这个问题,将第39行替换为:
//timer.lastCallTimestamp = Sys.time() * 1000;
timer.lastCallTimestamp = timer.lastCallTimestamp + timer.interval;https://stackoverflow.com/questions/226445
复制相似问题