如何在JINT Javascript端创建计时器

Nic*_*iff 4 javascript c# timer jint

我正在使用JINT(https://github.com/sebastienros/jint)开发一个C#项目,我需要在我的JS上创建一个计时器,这样每次定时器时间设置结束时它就能在我的javascript上执行一个函数.我怎么能做到这一点?我使用了setInterval或setTimeout函数,但似乎它们不是JINT的一部分,因为它基于ECMASCRIPT,并且这些函数不是本机的.

谁能告诉我怎么能这样做?

谢谢!!

use*_*830 7

无论是setIntervalsetTimeout被Jint,因为他们是在浏览器窗口API的一部分支持.使用Jint而不是浏览器,我们可以访问CLR,说实话,它更加通用.

第一步是在CLR端实现我们的Timer,这是一个用于内置int System.Threading.Timer类的极其简单的Timer包装器:

namespace JsTools
{
    public class JsTimer
    {
        private Timer _timer;
        private Action _actions;

        public void OnTick(Delegate d)
        {
            _actions += () => d.DynamicInvoke(JsValue.Undefined, new[] { JsValue.Undefined });
        }

        public void Start(int delay, int period)
        {
            if (_timer != null)
                return;

           _timer = new Timer(s => _actions());
           _timer.Change(delay, period);
        }

        public void Stop()
        {
            _timer.Dispose();
            _timer = null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

下一步是绑定JsTimer到Jint引擎:

var engine = new Engine(c => c.AllowClr(typeof (JsTimer).Assembly))
Run Code Online (Sandbox Code Playgroud)

这是一个用法示例:

internal class Program
{
    private static void Main(string[] args)
    {
        var engine = new Engine(c => c.AllowClr(typeof (JsTimer).Assembly))
            .SetValue("log", new Action<object>(Console.WriteLine))
            .Execute(
                @" 
var callback=function(){
   log('js');
}
var Tools=importNamespace('JsTools');
var t=new Tools.JsTimer();
t.OnTick(callback);
t.Start(0,1000);
");

        Console.ReadKey();
    }
}
Run Code Online (Sandbox Code Playgroud)