不使用JavaScript中的setTimeOut函数冻结浏览器

不使用JavaScript中的setTimeOut函数冻结浏览器

本文介绍了如何在不使用JavaScript中的setTimeOut函数冻结浏览器的情况下处理大循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个按钮.一个按钮名为"sync",另一个按钮名为"async".当我单击"sync"按钮时,它应使用循环处理大数组,并冻结浏览器,直到循环完成处理为止较大的数组.当我按下异步"按钮时,它应该处理相同的大型数组而不冻结浏览器.如何使用setTimeOut函数做到这一点?

I have created two buttons .One is named 'sync' and other is named 'async'.When i click 'sync' button ,it should process the big array using loops and it freezes the browser until the loop is completed processing the larger array.When i press the 'async' button.it should process the same large array without freezing the browser.How to do this using setTimeOut function?

推荐答案

您可以使用循环变量,如以下代码所示.在此示例中,该函数将每个元素加1.超时时间为1毫秒.

You can use a loop variable, like the following code. In this example, the function increases every element by 1. The timeout period is 1 millisecond.

    var currentIndex;
    function processNthElement(array) {
        if (currentIndex >= array.length)
        {
            //the whole array has been processed, do what you need to do
            //with the results here
            return;
        }

        //do what you want with the array element here
        array[currentIndex]++;

        currentIndex++;

        setTimeout(function () {
            processNthElement(array);
        }, 1);
    }
    function processArrayWithSetTimeout(array) {
        currentIndex = 0;
        processNthElement(array);
    }

然后要处理一个大数组,只需调用processArrayWithSetTimeout(array).但是,由于我们正在使用超时,因此您需要在最后一个函数调用时处理结果(请参见函数中的注释).如果数组包含10000个元素,则处理将花费10000毫秒或10秒以上的时间,但不会冻结UI.

Then to process a large array, just call processArrayWithSetTimeout(array). However since we are using timeout, you need to process the result at the very last function call(see the comment in the function). If an array has 10000 elements, it will take more than 10000 milliseconds or 10 seconds to process, but the UI won't be freezed.

请注意,它仍然按顺序处理数组,但不会冻结UI,因为它会在处理1个元素后等待一段时间.

Note that this still processes the array sequentially but without freezing the UI as it waits for a while after processing 1 element.

这篇关于如何在不使用JavaScript中的setTimeOut函数冻结浏览器的情况下处理大循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:12