異步實現數組排序

<script>
        // 寫一個函數sort()對數組arr排序
        var arr = [2, 3, 1, 11, 9, 5, 7, 4]
        function sort(arr, callback) {
            var _newArr = []
            var timer = null
            for (var i = 0; i < arr.length; i++) {
                time(arr[i])

            }
            timer = setInterval(function () {
                if (_newArr.length == arr.length) {
                    clearInterval(timer)
                    callback(_newArr)
                }
            }, 16)
            function time(num) {
                setTimeout(() => {
                    _newArr.push(num)
                }, num * 1000)
            }
        }
        
        var newArr
        sort(arr, function (param) {
            newArr = param
            console.log(newArr) // [1, 2, 3, 4, 5, 7, 9, 11]
        })
    </script>

複製代碼

相關文章
相關標籤/搜索