How to create a sleep/delay in nodejs that is Blocking?

后端 未结 12 635
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 07:00

I\'m currently trying to learn nodejs and a small project I\'m working is writing an API to control some networked LED lights.

The microprocessor controlling the LED

12条回答
  •  -上瘾入骨i
    2020-12-02 07:42

    asynchronous call ping command to block current code to execution in specified milliseconds.

    • ping command is Cross-platform
    • start /b means: start program but not show window.

    code as below:

    const { execSync } = require('child_process')
    // delay(blocking) specified milliseconds
    function sleep(ms) {
        // special Reserved IPv4 Address(RFC 5736): 192.0.0.0
        // refer: https://en.wikipedia.org/wiki/Reserved_IP_addresses
        execSync(`start /b ping 192.0.0.0 -n 1 -w ${ms} > nul`)
    }
    
    // usage
    console.log("delay 2500ms start\t:" + (new Date().getTime() / 1000).toFixed(3))
    sleep(2500)
    console.log("delay 2500ms end\t:" + (new Date().getTime() / 1000).toFixed(3))
    

    notice important: Above is not a precision solution, it just approach the blocking time

提交回复
热议问题