首页 > 编程语言 >[Javascript + Performance] How to run a large number of time-consuming tasks and doesn't block

[Javascript + Performance] How to run a large number of time-consuming tasks and doesn't block

时间:2024-08-24 16:37:26浏览次数:12  
标签:function consuming tasks run option task rendering runTask block

Try option 1: Promise 

Promise running in Microtask queue, and rendering should wait until the queue is empty; If you have a large number of time-consuming in microtask, it will also block rendering

function runTask(task) {
  Promise.resolve().then(() => {
    task()
  }) 
}

So this is NOT a soltuion.

 

Try option 2: SetTimeout

function runTask(task) {
  setTimeout(() => {
    task()
  }, 0) 
}

setTimeout run in Marctasks queue, it will block block the rendering but it will cause rendering to be laggy. Why?

for (;;) {
    // pick first task from marcotask queue
    // do the task
    // check whether it's good time to do the rendering? if yes then render
}

The reason it's not cause blocking rendering, due to everytime it only pick one task.

Laggy is due to different browser might have different handling logic, for example, Chrome might lag but Safari might not.

So setTimeout also doesn't seem to be a good option.

 

Try option 3: requestAnimationFrame

function runTask(task) {
  requestAnimationFrame(() => {
    task()
  }) 
}

It will block rendering for sure, becaue before each rendering, browser need to perform task()which will block rendering.

 

Try option 4: write custom code to (requestIdleCallback)

function _runTask(task) {
    requestIdleCallback(idle => {
        if (idle.timeRemaining()>0) {
            task()
        } else {
            _runTask(task)
        }
    })
}

function runTask(task) {
  _runTask(task)
}

The window.requestIdleCallback() method queues a function to be called during a browser's idle periods. This enables developers to perform background and low priority work on the main event loop, without impacting latency-critical events such as animation and input response. Functions are generally called in first-in-first-out order; however, callbacks which have a timeout specified may be called out-of-order if necessary in order to run them before the timeout elapses.

 https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback

It seems that requestidleCallbackcan perform the task well, there is no blocking render.

But there is a problem about browser support, https://caniuse.com/requestidlecallback, as you can see, not all the browsers support this API. If we want to support more browsers, we still need to improve it.

 

Try option 5: custom code with requestAnimationFrame

function _runTask(task) {
    const startTime = Date.now()
    requestAnimationFrame(() => {
        if (Date.now() - startTime < 16.6) {
            task()
        } else {
            _runTask(task)
        }
    })
}

function runTask(task) {
  _runTask(task)
}

We just need to calculate is there enough time to run the task, then we do it, otherwise wait for next tick. 

标签:function,consuming,tasks,run,option,task,rendering,runTask,block
From: https://www.cnblogs.com/Answer1215/p/18377928

相关文章

  • Android Kotlin优化代码整洁:with、applay以及run是什么,作用,区别
    目录为什么需要使用with、applay以及runwith、applay以及run是什么、作用以及三者区别一、为什么需要使用with、applay以及run我们在开发项目的过程当中,不可避免,一个界面的内容会有很多,如下initivew方法,会有Recyclerview的初始化,长按以及触摸事件设置,以及生命周期的注册,主......
  • STHTMLTestRunner
    #-*-coding:utf-8-*-"""ATestRunnerforusewiththePythonunittestingframework.ItgeneratesaHTMLreporttoshowtheresultataglance.Thesimplestwaytousethisistoinvokeitsmainmethod.E.g.importunittestimportHTML......
  • 安防视频监控EasyCVR视频汇聚平台出现代码层面报错“panic:runtime error”的原因排查
    安防视频监控/视频集中存储/云存储/磁盘阵列EasyCVR平台基于云边端一体化架构,兼容性强、支持多协议接入,包括国标GB/T28181协议、部标JT808、GA/T1400协议、RTMP、RTSP/Onvif协议、海康Ehome、海康SDK、大华SDK、华为SDK、宇视SDK、乐橙SDK、萤石云SDK等。有用户反馈,启动EasyCVR......
  • facefusion整合包cuda 环境报错解决: onnxruntime::ProviderLibrary::Get [ONNXRuntim
    在b站下载了一个up提供的facefusion整合包,运行go-web.bat报错报错信息如下:2024-08-1910:53:07.6316097[E:onnxruntime:Default,provider_bridge_ort.cc:1992onnxruntime::TryGetProviderInfo_CUDA]D:\a\_work\1\s\onnxruntime\core\session\provider_bridge_ort.cc:1637......
  • lazarus 3.4+fpc trunk编译tachart控件出错
    lazarus3.4+fpctrunk编译tachart控件出错原因:最新的fpc禁止访问private引起的修改方法:1、打开lazarus\components\tachart\tadatatools.pas将functionTDataPointDistanceTool.FindRef(APoint:TPoint;AMode:TDataPointMode;ADest:TDataPointTool.TPointRef;AOtherEndS......
  • gitlab runner远程连接其他服务器
    1、部署gitlabrunner2、 注册完成后 在代码仓库的根目录有一个流水线脚本 ......
  • pgsql登录不上,psql: error: connection to server on socket "/var/run/postgresql/.s
    背景在ubuntu上安装postgres,发现不能直接登录。分析默认是linux系统上的某个对应的用户才能使用对应的pg数据库的用户,因此我们需要作修改。解决编辑以下路径对应的文件,此处的14是版本,不知道的cd过去看看就行了。/etc/postgresql/14/main/pg_hba.conf将下图中对应位置改成m......
  • LoadRunner 12.55 解决录制 HTTPS网站,脚本空白问题
    背景:最近工作中项目有性能测试需求,但团队小伙伴用loadrunner12.55遇到https站点录制出来的脚本Action为空白,以往处理方式直接让项目团队将https改成http再重新录制痛点:修改http耗时长分析:项目web主要是内网使用,使用自签名证书,而loadrunner无该证书导致LoadrunnerProxyServer......
  • 《生化奇兵3》vcruntime140_1.dll丢失?推荐的vcruntime140_1.dll处理方式
    如果你在尝试运行“生化奇兵3”(BioShock3)这款游戏时遇到了丢失vcruntime140_1.dll文件的问题,可以采取以下几个步骤来解决这个问题。vcruntime140_1.dll文件简介vcruntime140_1.dll是MicrosoftVisualC++2015-2022Redistributable的一部分,用于支持使用VisualC++编译的应......
  • Docker无法运行java虚拟机报错There is insufficient memory for the Java Runtime
    镜像导入到docker后无法启动容器的问题,但是上传到别的服务器上面又可以正常启动容器,报错信息如下:#ThereisinsufficientmemoryfortheJavaRuntimeEnvironmenttocontinue.#CannotcreateGCthread.Outofsystemresources.#Cannotsavelogfile,dumptoscree......