Created
March 21, 2015 19:56
-
-
Save rainkinz/05873fb5dbd8d1ce5959 to your computer and use it in GitHub Desktop.
setTimeout using libuv and therubyracer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'bundler/setup' | |
require 'v8' | |
require 'libuv' | |
require 'pry' | |
# class Global | |
# attr_reader :console | |
# def initialize(event_loop) | |
# @event_loop = event_loop | |
# @console = Console.new | |
# end | |
# def setTimeout(fn, timeout) | |
# puts "Running function #{fn} with timeout #{timeout}" | |
# timer = @event_loop.timer do | |
# fn.call | |
# timer.close | |
# end | |
# timer.start(timeout) | |
# end | |
# end | |
class Console | |
def log(msg) | |
puts msg | |
end | |
end | |
script = <<-EOS | |
var broadcast = function(msg, timeout, callback) { | |
setTimeout(function() { | |
console.log(msg); | |
callback(); | |
}, timeout); | |
}; | |
broadcast("Is there anyone there?", 1000, function() { | |
console.log("Message sent"); | |
}); | |
EOS | |
@event_loop = Libuv::Loop.default | |
@event_loop.run do | |
# V8::Context.new(:with => Global.new(event_loop)) do |ctx| # Blows chunks | |
V8::Context.new do |ctx| | |
ctx['setTimeout'] = lambda do |this, fn, timeout| | |
puts "Running function #{fn} with timeout #{timeout}" | |
timer = @event_loop.timer do | |
fn.call | |
timer.close | |
end | |
timer.start(timeout) | |
end | |
ctx['console'] = Console.new | |
ctx.eval(script) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment