Created
May 7, 2020 11:26
-
-
Save Validark/0b250dbdf150ff1b4b9c8607a9390c13 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| local RunService = game:GetService("RunService") | |
| local delay do | |
| -- uses a sorted singly linked list (queue) to achieve O(1) remove operations and O(n) for insert | |
| local first -- the initial node in the linked list | |
| local connection -- the Heartbeat `RBXScriptConnection | nil` | |
| function delay(seconds, resolve) | |
| assert(type(seconds) == "number", "Bad argument #1 to delay, must be a number.") | |
| -- If seconds is -INF, INF, NaN, or less than 1 / 60, assume seconds is 1 / 60. | |
| -- This mirrors the behavior of wait() | |
| if not (seconds >= 1 / 60) or seconds == math.huge then | |
| seconds = 1 / 60 | |
| end | |
| local startTime = tick() | |
| local endTime = startTime + seconds | |
| local node = { | |
| resolve = resolve, | |
| startTime = startTime, | |
| endTime = endTime | |
| } | |
| if connection == nil then -- first is nil when connection is nil | |
| first = node | |
| connection = RunService.Heartbeat:Connect(function() | |
| local currentTime = tick() | |
| while first.endTime <= currentTime do | |
| first.resolve(currentTime - first.startTime) | |
| first = first.next | |
| if first == nil then | |
| connection:Disconnect() | |
| connection = nil | |
| break | |
| end | |
| currentTime = tick() | |
| end | |
| end) | |
| else -- first is non-nil | |
| if first.endTime < endTime then -- if `node` should be placed after `first` | |
| -- we will insert `node` between `current` and `next` | |
| -- (i.e. after `current` if `next` is nil) | |
| local current = first | |
| local next = current.next | |
| while next ~= nil and next.endTime < endTime do | |
| current = next | |
| next = current.next | |
| end | |
| -- `current` must be non-nil, but `next` could be `nil` (i.e. last item in list) | |
| current.next = node | |
| if next ~= nil then | |
| node.next = next | |
| end | |
| else | |
| -- set `node` to `first` | |
| node.next = first | |
| first = node | |
| end | |
| end | |
| end | |
| end | |
| delay(3, print) | |
| delay(5, print) | |
| delay(4, print) | |
| delay(2, print) | |
| delay(1, print) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment