最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to create timer on JINT Javascript side - Stack Overflow

programmeradmin0浏览0评论

I´m developing a C# project using JINT (), and I need to create a timer on my JS so it can execute a function on my javascript every time the timer tim set is elapsed. How can I acplish that?. I have used setInterval or setTimeout functions but it seems that they are not part of JINT since it is based on ECMASCRIPT and this functions are not native.

Can someone tell me how I can do this?.

Thanks!!

I´m developing a C# project using JINT (https://github./sebastienros/jint), and I need to create a timer on my JS so it can execute a function on my javascript every time the timer tim set is elapsed. How can I acplish that?. I have used setInterval or setTimeout functions but it seems that they are not part of JINT since it is based on ECMASCRIPT and this functions are not native.

Can someone tell me how I can do this?.

Thanks!!

Share Improve this question asked Nov 27, 2015 at 16:58 NicoRiffNicoRiff 4,8833 gold badges29 silver badges57 bronze badges 1
  • There is an extension package that claims to offer just that and more: github./fredericaltorres/Jint.Ex – djk Commented Jul 20, 2017 at 19:05
Add a ment  | 

1 Answer 1

Reset to default 10 +50

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();
    }
}
发布评论

评论列表(0)

  1. 暂无评论