简体   繁体   English

JS异步功能停止页面加载

[英]JS Async Function Stops Page Loading

I have a single page with a table. 我只有一张桌子。 On Page load this table will get updated with data. 在页面加载时,此表将更新数据。 I need something resembling a thread once table is created so that is can be refreshed every few seconds. 创建表后,我需要类似于线程的内容,以便每隔几秒钟刷新一次。

At the moment once the data is fetched on ajax call. 目前,一旦通过ajax调用获取了数据。 If i call asyncThread() the table doesnt load on the page, the UI is hung and stuck in a loop. 如果我调用asyncThread(),则表不会加载到页面上,UI将被挂起并陷入循环中。 How do i prevent the UI hanging when calling the asyncThread() function ? 调用asyncThread()函数时如何防止UI挂起?

 $.ajax({
                url: 'xxxxxxxxx',
                contentType: 'application/html ; charset:utf-8',
                type: 'GET'
            }).success(function (result) {
                $('#table')
                    .DataTable(
                        {
                            paging: false,
                            "ordering": false,
                            "language": {
                                "decimal": ",",
                                "thousands": "."
                            },
                            searching: false,
                            "scrollCollapse": true,
                            "scrollY": "75vh"
                        });
                asyncThread();
            }).error(function () {

            });

.

    async function asyncThread() {
        while (true) {
            console.log('loop started');
            setTimeout(function () {
                console.log('sleep');
            }, (3 * 1000))
        }           

    }

Let's first analyze your asyncThread method 首先让我们分析一下asyncThread方法

async function asyncThread() {
    while (true) {
        console.log('loop started');
        setTimeout(function () {
            console.log('sleep');
        }, (3 * 1000))
    }           

}

What you are doing here, shows that you lack the understanding of how the JavaScript engine works: 您在这里所做的事情表明您对JavaScript引擎的工作原理缺乏了解:

  • JavaScript is single threaded. JavaScript是单线程的。
  • async methods return an implicit promise, they don't really run asynchronous per say async方法返回一个隐式的Promise,它们实际上并不是说异步运行
  • Your while loop will run indefinitely, your setTimeout function will never be executed, as this would only happen when you the JavaScript engine gets time to execute something else (which it can't, as it is stuck in your while loop) 您的while循环将无限期地运行,您的setTimeout函数将永远不会执行,因为只有当JavaScript引擎有时间执行其他操作时,这种情况才会发生(它无法执行,因为它被卡在while循环中)

Typically, for these polling requests, you would rely on setInterval or setTimeout . 通常,对于这些轮询请求,您将依赖setIntervalsetTimeout The first will periodically execute a function until clearInterval is called or the page is unloaded, the second will run once unless clearTimeout was called before the timeout expires. 第一个将定期执行一个函数,直到调用clearInterval或页面被卸载为止,第二个将运行一次,除非在超时到期之前调用clearTimeout

async denotes that the function will give back a promise, which you could then handle through the promise chain, or from a different async method, you could await its successful completion async表示该函数将返回一个promise,然后可以通过promise链进行处理,或者通过其他async方法,您可以await其成功完成

Well, you have infinite loop while (true) {...} which is blocking main thread. 好吧,你有无限循环, while (true) {...}阻塞了主线程。 I think, what you looking for is 我想,你要找的是

function asyncThread() {
    console.log('loop started');
    setTimeout(() => {
        console.log('sleep');
        asyncThread();
    }, 3000)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM