如何在 JINT Javascript 端创建计时器 [英] How to create timer on JINT Javascript side

查看:22
本文介绍了如何在 JINT Javascript 端创建计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I´m developing a C# project using JINT (https://github.com/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 accomplish 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?.

谢谢!!

推荐答案

Jint 不支持 setIntervalsetTimeout,因为它们是浏览器中 Window API 的一部分.使用 Jint,我们可以访问 CLR,而不是浏览器,而且说实话,它的用途要广泛得多.

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.

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

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

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

Next step is to bind out JsTimer to Jint engine:

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

这是一个用法示例:

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

这篇关于如何在 JINT Javascript 端创建计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆