How to create timer on JINT Javascript side

那年仲夏 提交于 2019-12-05 13:44:31

Neither setInterval and setTimeout are supported by Jint because they are part of the Window API in browsers. with Jint, instead of browser, we have access to CLR, and to be honest it's much more versatile.

First step is to implement our Timer in CLR side, Here is an extremely simple Timer wrapper for built-int System.Threading.Timer class:

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;
        }
    }
}

Next step is to bind out JsTimer to Jint engine:

var engine = new Engine(c => c.AllowClr(typeof (JsTimer).Assembly))

Here is an usage example:

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();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!