Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: Calling javascript which uses setTimeout/setInterval

0
0
Greetings!

ClearScript provides a bare JavaScript environment, whereas the functions you're looking for are part of the Web API, which is typically provided by web browsers.

The functions are relatively easy to implement, but because they provide asynchronous operations, the implementation may depend on your application's threading model.

Here's an example that uses .NET timers under the covers and should work in typical multithreaded .NET applications. First, a simple .NET class that provides timer access and can route callbacks to script code:
publicstaticclass ScriptTimer {
    publicstaticobject Create(dynamic func, double delay, double period, object args) {
        var callback = new TimerCallback(state => func.apply(null, args));
        returnnew Timer(callback, null, Convert.ToInt64(delay), Convert.ToInt64(period));
    }
}
Next, script functions that use the class to provide the required behavior:
engine.AddHostType("ScriptTimer", typeof(ScriptTimer));
engine.Execute(@"
    function createTimer(periodic, func, delay) {
        var period = periodic ? delay : -1;
        var args = Array.prototype.slice.call(arguments, 3);
        return ScriptTimer.Create(func, delay, period, args);
    }
    setTimeout = createTimer.bind(null, false);
    setInterval = createTimer.bind(null, true);
    clearTimeout = function(id) { id.Dispose(); };
    clearInterval = clearTimeout;
");
Again, this implementation may not be right for your application, but hopefully it gives you an idea of how .NET and script code can work together to provide whatever functionality you need.

Good luck!

Viewing all articles
Browse latest Browse all 2297