-
-
Save apeiros/500d3188a81f133f1df9 to your computer and use it in GitHub Desktop.
Recreate a browser's run-loop
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
# The code ported to ruby | |
results = [] | |
rounds = 5 | |
callback = (result) -> | |
results.push result | |
if results.length is rounds | |
console.log "All #{rounds} requests have completed! Here they are:", results | |
[1 .. rounds].forEach (item) -> | |
setTimeout (-> callback(item)), item * 1000 | |
console.log "This line should appear on top of the output" |
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
require 'runner' | |
Runner.new do | |
results = [] | |
rounds = 5 | |
callback = ->(result) { | |
results.push result | |
if results.size == rounds | |
puts "All #{rounds} requests have completed! Here they are:", *results | |
end | |
} | |
1.upto(rounds) do |item| | |
timeout 0 do callback.call(item) end | |
end | |
puts "This line should appear on top of output" | |
end |
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
class Runner | |
Delayed = Struct.new(:id, :execute_at, :reschedule, :work) do | |
def <=>(other) | |
execute_at <=> other.execute_at | |
end | |
end | |
def initialize(&block) | |
@id = 0 | |
@delayed = [] | |
if block | |
instance_eval(&block) | |
run | |
end | |
end | |
def timeout(milliseconds, &work) | |
@delayed << Delayed.new(@id+=1, Time.now+milliseconds.fdiv(1000), nil, work) | |
@delayed.sort! | |
end | |
def intervall(milliseconds, &work) | |
@delayed << Delayed.new(@id+=1, Time.now+milliseconds.fdiv(1000), milliseconds, work) | |
@delayed.sort! | |
end | |
def clear_timeout(id) | |
@delayed.delete_at(@delayed.find_index { |work| work.id == id }) | |
end | |
def run | |
until @delayed.empty? | |
delayed = @delayed.shift | |
delayed.work.call | |
if delayed.reschedule | |
delayed.execute_at = Time.now+delayed.reschedule.fdiv(1000) | |
@delayed << delayed | |
@delayed.sort! | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment