Delay Javascript without using setTimeout

advertisements

I am writing a MongoDB stored javascript script. This context does not appear to allow the setTimeout method to be used.

Within my script I need to issue a set number of database updates at 10ms intervals (the script will take around 5 seconds to run, but each document update must be spaced by around 10ms).

What is the best way to space the updates by 10ms without using the setTimeout technique? The script will be running on a local workstation, not a server, so locking up the machine for a few seconds won't be a disaster.


Don't know about mongoDB specifically, but you can force a script delay with the following code.

Obviously this will lock up the script while running, so is generally not recommended, but may be valid for your specific requirements in this case:

    function delay(ms) {
        var limit = new Date();
        limit = limit.setMilliseconds(limit.getMilliseconds() + ms);
        while ((new Date()) < limit) {
            // do nothing
            ;
        }
    }

    console.log((new Date()).getMilliseconds());
    delay(150);
    console.log((new Date()).getMilliseconds());