正如每个Haxe开发人员都知道的那样,您可以使用 haxe.Timer.delayed()来延迟函数调用一段时间。但Neko根本不存在这个功能。有没有办法达到同样的效果?

有帮助吗?

解决方案

必须先检查,但

function delayed(f, time) {
   neko.vm.Thread.create(function() {
       neko.Sys.sleep(time);
       f();
   });
}

可能是最接近的事情。唯一的缺点是应用程序变得多线程,这可能导致严重的问题。

其他提示

我考虑过你的问题,我认为最好的方法是为Neko创建自己的Timer类。我为你做了一个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设置来增加它。

我也使用了这门课,我发现了一个问题。因为不完全是实时的,它会睡眠间隔,调用函数,并再次睡眠间隔。因此,根据您运行的函数所花费的时间,它会更慢或更快。

我已经通过更换第39行解决了这个问题:

//timer.lastCallTimestamp = Sys.time() * 1000;
timer.lastCallTimestamp = timer.lastCallTimestamp + timer.interval;

是的,除了你在第一个答案中提到的内容,我什么都不知道。在Linux上你可以使用SIGALARM - 但这看起来并不简单,100%纯C代码,需要小心处理以避免崩溃VM。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top