Lets say I have a really heavy piece of computation, it involves two nested for loops goings over an array of size 1000*1000
The calculation takes about 1 minute to do.
I have a bunch of other stuff going on in the webpage especially user interaction. ( on-click, on-scroll, animation, etc )
Now I need to do the 60s calculation at some point. I can for example do:
setTimeout TwoForLoops,0this will defer the function call to until all the other on-click,on-scroll,etc events are cleared. however as the calculation takes 1 Minute, the user might trigger some event during that time. do you think if I just do the following I will prevent JavaScript from hanging. Assuming that heavyComputation takes about 0.06 millisecond to computate.
# _.map is from underscore@ library, basically does a for loop # HeavyComputation is a slow function with lots of operations made for my app NonBlockMap = (x,f)-> setTimeout (->_.map x,f),0 NonBlockHeavyComputation = (x) -> setTimeout (-> HeavyComputation(x)),0 TwoForLoops = (ArrayOfArray) -> SecondLoop = (element) -> NonBlockHeavyComputation element FirstLoop = (array) -> NonBlockMap array, SecondLoop return NonBlockMap ArrayOfArray,FirstLoopThis would essentially mean that the maximum javascript will hang for is about 0.06 millisecond but I am not so sure if this will work.
WhatDo ?
Deferring all heavy computation using setTimeout
369 Views Asked by sourcevault At
1
There are 1 best solutions below
Related Questions in JAVASCRIPT
- Using Puppeteer to scrape a public API only when the data changes
- inline SVG text (js)
- An array of images and a for loop display the buttons. How to assign each button to open its own block by name?
- Storing the preferred font-size in localStorage
- Simple movie API request not showing up in the console log
- Authenticate Flask rest API
- Deploying sveltekit app with gunjs on vercel throws cannot find module './lib/text-encoding'
- How to request administrator rights?
- mp4 embedded videos within github pages website not loading
- Scrimba tutorial was working, suddenly stopped even trying the default
- In Datatables, start value resets to 0, when column sorting
- How do I link two models in mongoose?
- parameter values only being sent to certain columns in google sheet?
- Run main several times of wasm in browser
- Variable inside a Variable, not updating
Related Questions in ASYNCHRONOUS
- Callback and Microtask Queue of Java Script
- Occasional crash at NSURLSessionDataTask dataTaskWithRequest:completionHandler:
- Musical chairs: How can an asynchronous task cancel a synchronous one in c#?
- Asynchronously add to queue, synchronously process it
- Sending asynchronous requests without a pre-defined task list
- Value of a variable remains unaltered when assigned during a loop
- How to efficiently test some HTTP proxies for accessing a specific domain?
- How do you update Celery Task State/Status to see it in Flower?
- Why use tasks and async await in C# inline?
- NEXTJS14 DRIZZLE : Async issue when trying to post data from component into DB
- Blocking wait on future OUTSIDE of async functions
- save to csv simultaneously opcua datachange notification
- How can I load data from secrets-manager synchronously in TypeScript
- How to avoid timeout of API before ending?
- Conditional Synchronous Import in JavaScript, to export a simple object and not promise, possible?
Related Questions in COFFEESCRIPT
- ExecJS::RuntimeError with rails, how get details of error?
- How to correctly use functions inside loops in CoffeeScript 2?
- How to instantiate a class that requires DOM with Puppeteer?
- Find Model in Backbone
- How can I compile CoffeeScript from .NET using Visual Studio 2022?
- Searching for emails with empty subjects using IMAP
- How do I find memory leak in my node.js application on Heroku?
- Übersicht (macOS) question: prevent image caching in widget
- Troubleshooting Issues with PDF Conversion in Updated Docker-Wkhtmltopdf-aas Package
- Cannot import coffee-script file into application.js
- export, import, use class with coffeescript in rails5 app
- Why does installing grunt(npm install grunt --save-dev) into my project stops in between and doesn't make any chnages to package.json?
- how put an id unique in a button in a rails loop?
- Prioritize Gmail filter using Gmail API
- Passing json from rails to coffeescript
Related Questions in UNDERSCORE.JS
- Arguments object not working on Underscore first type function
- Uncaught TypeError: App.Routers.Maintenances.MyRouter is not a constructor
- Error type DeepTypeOfCollection is not generic
- Issue with the instantiation of the object _
- Google Map data driven styling for fill boundary for multi State - not working as expected
- Why _.clone() doesn't copy object methods?
- Why do sites that use lodash or underscore not work in Opera?
- Returning the last computed result in a throttled function
- How to skip over the first iteration when one argument is undefined?
- _lodash, sort by 2 fields(numbers, time)
- Merge array of objects with array values into a single object
- How to chain Underscore methods to populate an object from nested array?
- Having a problem with rewriting invoke function inspired by underscore library
- Javascript find objects that contain matching elements from arrays in another object
- Using Underscore.js with require.js: Uncaught ReferenceError: _ is not defined
Related Questions in NONBLOCKING
- Improving Django Application Performance: Comparing Blocking and Non-blocking Implementations
- Create non blocking sockets in Octave
- How to perform a non-blocking write to a USB HID device?
- What is the minimum number of written bytes of a SocketChannel when its key is writable?
- Why is MPI_Bsend() a blocking function?
- Is Python's `print()` function blocking or non-blocking?
- Why this promise never gets resolved?
- What exactly makes a non-blocking socket block? The possible danger of using epoll() in edge-triggered mode
- epoll not receiving `EPOLLIN` signal when server sends data to tcp client
- pure C++ design pattern non-blocking for loop
- Is my code thread-safe? [Java, CAS, money transfer]
- Suspend keyword as redundant with Network Request function in Spring Boot Application
- Virtual thread for reading InputStream from HTTP response
- python request blocks publishing of mqtt messages
- Spring reactive r2dbc - how to loop first query which returns Flux<String> and call second query which returns Flux<Object> in non blocking way?
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular # Hahtags
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
I think your code queues all million HeavyComputation continuables up front, not as it progreses. The event loop will process each one in order before handling new user events, so you've still blocked for a minute.
You should use setImmediate though, or double-check that setTimeout of 0 does not sleep. Nodejs (what I work in; maybe chrome too?) always sleeps 1 ms.
Consider batching the heavy computation nested loop, something like: