javascript 睡眠排序(https://dev.to/sishaarrao/sleep-sort-where-theory-meets-sobering-reality-b3m)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 睡眠排序(https://dev.to/sishaarrao/sleep-sort-where-theory-meets-sobering-reality-b3m)相关的知识,希望对你有一定的参考价值。

function sleepSort(array/* : int[] */, cb) {
    var result = []
    array.forEach(i => {
        setTimeout(() => {
            result.push(i)
            if (result.length === array.length) cb(result)
        }, i * 1000) // it doesn't need to sleep this long, but it's consistent with bash version
    })
}
function sleepSortFast(array/* : float[] */, cb) {
    var maxDigits = array.reduce((result, i) => {
      var digits = (('' + i).match(/\d+\.?(\d*)$/) || [null, ''])[1].length
      return Math.max(result, digits)
    }, 0)
    var delayFactorMs = (Math.pow(10, maxDigits)) // how long we have to wait
    var result = []
    array.forEach(i => {
        setTimeout(() => {
            result.push(i)
            if (result.length === array.length) cb(result)
        }, (i * delayFactorMs) + (i * 10)) // a bit of buffer time
    })
}

以上是关于javascript 睡眠排序(https://dev.to/sishaarrao/sleep-sort-where-theory-meets-sobering-reality-b3m)的主要内容,如果未能解决你的问题,请参考以下文章

js 睡眠排序

一个有趣的排序算法—睡眠排序

JavaScript在继续之前睡眠/等待[重复]

javascript 简单的JavaScript睡眠功能

JavaScript Javascript中的睡眠/延迟

JavaScript中有睡眠功能吗? [复制]