aboutsummaryrefslogtreecommitdiff
path: root/utils/delayUtils.js
blob: 3ec6d95b426eec1e592dd5d76d8d9ab5928a9098 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const { default: FlatQueue } = require("../datastructures/flatqueue")

if (!global.delayThingSoopy) {

    let functionQueue = new FlatQueue()
    let functions = new Map()
    let functionId = 0

    function delay(time, callback) {
        let id = functionId++
        functions.set(id, callback)
        functionQueue.push(id, Date.now() + time)
    }

    register("tick", () => {
        while (functionQueue.length > 0 && Date.now() > functionQueue.peekValue()) {
            let id = functionQueue.pop()

            functions.get(id)()
            functions.delete(id)
        }
    })

    global.delayThingSoopy = {
        delay: delay
    }
}

module.exports = global.delayThingSoopy