Synchronous delay in code execution

前端 未结 10 1182
长情又很酷
长情又很酷 2020-12-03 02:29

I have a code which needs to be executed after some delay say 5000 ms.Currently I am using setTimeout but it is asynchronous and i want the execution to wait for its return.

10条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 03:06

    Node solution

    Use fs.existsSync() to delay

    const fs = require('fs');
    const uuidv4 = require('uuid/v4');
    
    /**
     * Tie up execution for at-least the given number of millis.  This is not efficient.
     * @param millis Min number of millis to wait
     */
    function sleepSync(millis) {
        if (millis <= 0) return;
        const proceedAt = Date.now() + millis;
        while (Date.now() < proceedAt) fs.existsSync(uuidv4());
    }
    

    fs.existsSync(uuidv4()) is intended to do a few things:

    1. Occupy the thread by generating a uuid and looking for a non-existent file
    2. New uuid each time defeats the file system cache
    3. Looking for a file is likely an optimised operation that should allow other activity to continue (i.e. not pin the CPU)

提交回复
热议问题