requestidlecallback | Cooperative Scheduling of Background Tasks | Job Scheduling library
kandi X-RAY | requestidlecallback Summary
kandi X-RAY | requestidlecallback Summary
Cooperative Scheduling of Background Tasks
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample of requestidlecallback
requestidlecallback Key Features
requestidlecallback Examples and Code Snippets
Community Discussions
Trending Discussions on requestidlecallback
QUESTION
In a browser, I am trying to make a well-behaved background job like this:
...ANSWER
Answered 2020-Jul-25 at 17:23I think this is really dependent on what exactly you are trying to achieve though.
For example, you could initialize your web-worker on loading the page and make it run the background-job, if need be, then communicate the progress or status of the job to the main thread of your browser. If you don't like the use of post-message
for communication between the threads, consider user Comlink
However, if the background job you intend to do isn't something worth a web-worker. You could use the requestIdleCallback
API. I think it fits perfectly with what you mentioned here since you can already make it recursive. You would not need a timer anymore and the browser can help you schedule the task in such a way that it doesn't affect the rendering of your page (by keeping everything with 60fps).
Something like =>
QUESTION
I have the following function, that zooms out on images once they enter the viewport. All images are lazyloaded, which is why I want to start the zooming behavior only when the image is fully visible. The event to listen to is called 'lazyunveilread'. Then there is a css transition to fade in the image. Once both things are done, the zooming should be initialized.
Unfortunately, I don't know how to do that. I tried installing the event listener on the event but that only works for the first element and not for the others.
...ANSWER
Answered 2020-May-29 at 12:32So I changed your markup a little bit:
QUESTION
Are functions passed to requestIdleCallback
guaranteed to run when no timeout
is specified? (Assuming we aren't in some contrived scenario, specifically engineered to avoid idle state indefinitiely)
And if a timeout
is specified, is there a guarantee around order of execution? e.g.
ANSWER
Answered 2020-May-04 at 06:55Cooperative Scheduling of Background Tasks says:
During an idle period the user agent will run idle callbacks in FIFO order until either the idle period ends or there are no more idle callbacks eligible to be run. As such, the user agent will not necessarily run all currently posted idle callbacks within a single idle period. Any remaining idle tasks are eligible to run during the next idle period.
Therefore, I believe with your example, fnOne
, fnTwo
and fnThree
would be executed in that order.
QUESTION
This is a bizarre one. We have a Laravel website, and on said site we have a timer per user, where they get 15 minutes of being inactive before being booted.
We do this through a timer that sits on the page in a react component, it works as we want it to, but now we have a new issue: If a user is logged in and shut the lid of their laptop the website should boot them. Banks do this, Schools and Universities do this, Government sites also do this. So it is possible, just not sure how.
We do use web sockets, using laravel-websockets library and Echo. What I would like to see happen is:
- Once you close your laptop boot you to the login screen. So the next time you open the laptop and login, and see the browser you are on the login screen. It doesn't have to happen that quickly, but we need a way to send something to the front end basically telling them to refresh the page, once the session is killed, we set the session lifetime on laravel of 15 minutes.
Some people have suggested in other similar questions:
- to create a custom web-socket handler
- To compare the session cookie (in the browser) with the user cookie on the back end.
- To have a timer running on the front end (we do, it just stops when you close the laptop lid)
The most popular one seems to be using web-sockets, listening for the user to disconnect and then boot them, which is fine and all, but then how do you send a request to a browser thats suspended to then boot them?
I have found requestIdleCallback() But again, I don't think this is what I want if I already have a heartbeat timer on the site. It also doesn't work in all browsers.
I am very lost here on how to accomplish this, the example I can give is:
Log in to your bank, put your computer to sleep, wait 15-20 minutes, awaken the computer, log in and see your bank now has you on the login screen. That's what I want. But I don't know how to accomplish that.
You cant send events to a "sleeping" browser from the back end, and while yes this would have to be a back end solution, how do you update the front end then, so that they are on the logout screen when they reawaken the laptop or computer?
...ANSWER
Answered 2020-Mar-23 at 20:31So Idea is behind setInterval and Sockets, setInterval is supported in most browsers and javascript WbsocketApi is supported in almost everybrowser.
Brief overview: setInterval() - this function behaviour is following when your computer is at sleep/suspended/hibernate mode it is paused and when you are at awaken mode it resumes itself.
The following code does the following, at first(maybe at the same time but) it starts php server_socket listening to the connections,
than javascript websocket api sends current timestamp in Unix timestamp milliseconds in every 2 seconds you can have 1 second it is up to you.
after that php server socket is getting this time and checks if it has anything like previous time to compare, when the code is first instantiated php does not has anything like previous time to compare it to the time which was sent from javascript websocket, so php does nothing but saves this time in the session called 'prev_time' and waits for another time data to be recieved from javascript socket, so here begins second cycle.
when php server socket new time data from javascript WebsocketApi it checks it has anything like previous time to compare to this newly received time data, it means that php checks if session called 'prev_time' exists, as we are in the second cycle php discovers that it exists, grabs it's value and does following $diff = $new_time - $prev_time
, $diff will be 2 seconds or 2000 miliseconds because remember our setInterval cycle happens in every 2 seconds and time format we are sending is in miliseconds,
than php checks if($diff<3000)
if difference is less than 3000 if it is it knows that user is active, again you can manipulate this seconds as you wish, I choose 3000 because possible latency in the network which is almost impossible but you know I am always cautious when it comes to networks, so let's continue, when php determines that user is active php just resets 'prev_time' session with the value of $new_time
which was newly received and just for testing purposes it sends message back to javascript socket,
but if $diff
is more than 3000 it means that something paused our setInterval and there is only way it can happen and I think you already know what I am saying, so in the else
logic of ( if($diff<3000)
) you can logout user by destroying specific session and if you want to redirect you can send some text to javacript socket and create a logic which will execute window.location = "/login"
depending on the text, that's it here is the code:
First it is index.html file just to load javascript:
QUESTION
In my React-App (create-react-app) I use a selector (created with reselect) to compute derived data from stored data.
The Problem is, the selector takes a long time to compute. I would like to show a spinner (or a message) on the user interface. But each time the selector is recomputed the ui freezes.
I read a lot of stuff (Web Worker, requestIdleCallback, requestAnimationFrame) and try to make my own React hook but I am stuck. I cannot use the selector in callbacks.
The searched result is simply to get the ui refreshed before the selector is recomputed.
...ANSWER
Answered 2020-Mar-19 at 09:41That's my solution. I don't know if it's "good" or if it breaks some rules of react or reselect, but it works. Maybe you can assess that?
The code is simplified to improve readability.
The idea is, the selector returns a Promise and I call requestAnimationFrame
before computing the data to get a chance to refresh the ui.
selector.js:
QUESTION
As we know, it's often advised to debounce scroll listeners so that UX is better when the user is scrolling.
However, I've often found libraries and articles where influential people like Paul Lewis recommend using requestAnimationFrame
. However as the web platform progress rapidly, it might be possible that some advice get deprecated over time.
The problem I see is there are very different use-cases for handling scroll events, like building a parallax website, or handling infinite scrolling and pagination.
I see 3 major tools that can make a difference in term of UX:
So, I'd like to know, per usecase (I only have 2 but you can come up with other ones), what kind of tool should I use right now to have a very good scroll experience?
To be more precise, my main question would be more related to infinite scrolling views and pagination (which generally do not have to trigger visual animations, but we want a good scrolling experience), is it better to replace requestAnimationFrame
with a combo of requestIdleCallback
+ passive scroll event handler ? I'm also wondering when it makes sense to use requestIdleCallback
for calling an API or handling the API response to let the scroll perform better, or is it something that the browser may already handle for us?
ANSWER
Answered 2019-Nov-03 at 17:37Although this question is a little bit older, I want to answer it because I often see scripts, where a lot of these techniques are misused.
In general all your asked tools (rAF
, rIC
and passive listeners) are great tools and won't vanish soon. But you have to know why to use them.
Before I start: In case you generate scroll synced/scroll linked effects like parallax effects/sticky elements, throttling using rIC
, setTimeout
doesn't make sense because you want to react immediately.
requestAnimationFrame
rAF
gives you the point inside the frame life cycle right before the browser wants to calculate the new style and layout of the document. This is why it is perfect to use for animations. First it won't be called more often or less often than the browser calculates layout (right frequency). Second it is called right before the browser does calculate the layout (right timing). In fact using rAF
for any layout changes (DOM or CSSOM changes) makes a lot of sense. rAF
is synced with the V-SYNC as any other layout rendering related stuff in the browser.
rAF
for throttle/debounce
The default example of Paul Lewis looks like this:
QUESTION
Update: Similiar question with a very good answer that shows how to use requestAnimationFrame with scroll in a useful way: scroll events: requestAnimationFrame VS requestIdleCallback VS passive event listeners
So let's say I want to add some expensive action on my site triggered by scrolling. For example, I'm using parallax effects in my jsfiddle.
Now I keep reading it must not be bound to the event directly, sometimes followed by snippets that are meant to be better. Just some examples:
- Attaching JavaScript Handlers to Scroll Events = BAD!
- How to develop high performance onScroll event?
- How to make faster scroll effects?
- 60FPS onscroll event listener
What they say is basically don't do this:
...ANSWER
Answered 2018-Jul-20 at 09:24I am not totally sure if I got correctly your questions and all your statements but I will try to give you an answer:
- Am I missing something or is this a valid test? If it's invalid, how could I test correctly?
It is a valid test if you are measuring the number of times a function has been called, this will of course depend on the browser, SO, if is GPU enhanced and some other benchmark parameters that has been commented in your question already.
If we consider that measurement correct then it can be said that by using timeouts or requestAnimationFramework could save time because we are basically following the principles of debouncing or throttling. Basically we do not want to request or called a function more times than is needed. In the case of the timer we will queue less functions calls and in the case of requestAnimationFrame because it enqueue calls before repainting and will execute them sequentially. In timeouts it could happen that calculations overlap if they are very heavy.
I found a better answer in why using requestAnimationFrame explaining the main problems with animations in the browser like Shear, flickering or frame skip. It also includes a good demo.
I think your testing method is correct, you also should interpret it correctly, maybe calls are close to be the same number because of your hardware and your engine, but as said, debounce and throttling are a performance relieve.
Here also one more article supporting not attach handlers to window scroll from Twitter. (Disclaimer: this article is from 2011 and browsers have deal with optimizations for scroll in different ways).
- why is everyone nervous about onscroll? If fluid animations require 5000 calculations over the complete site, there's no way to change it anyway?
I do not think there is nervousness in the performance hit, but the user experience will be worst for the above mentioned animation problems that your overcalling of scroll can cause, or even if there is a desynchronization with your timer you could still get the same 'performance' problems. People just recommend saving calls to scroll because: Human visual permanence doesnt require a super high frame rate and so it is useless to try to show images more often. For more complex calculations or heavy animations browsers are already working on optimizations, like you have check, some browsers had optimize this things in comparison with the 2, 3 or 6 years ago the articles you expose were written.
QUESTION
Let’s imagine I have a function to handle requestIdleCallBack
and a greetings function :
ANSWER
Answered 2018-Nov-06 at 03:20The standard bind
method can do this:
QUESTION
I thought that our code gets about 16ms of time to execute, since the rendering rate is 60 fps, so 1000 /60 = ~16ms. However, if I run this in Chrome:
...ANSWER
Answered 2018-Oct-30 at 08:24The spec supports your assumption. In Start an idle period algorithm it says:
- Let deadline be a time in the future until which the browser expects to remain idle. The user agent should choose deadline to ensure that no time-critical tasks will be delayed even if a callback runs for the whole time period from now to deadline. As such, it should be set to the minimum of: the closest timeout in the list of active timers as set via setTimeout and setInterval; the scheduled runtime for pending animation callbacks posted via requestAnimationFrame; pending internal timeouts such as deadlines to start rendering the next frame, process audio or any other internal task the user agent deems important.
(my emphasis)
So if there were an internal pending timeout to render the next frame, the deadline would have to be before then.
QUESTION
I'm trying to measure the user-perceived latency of an interaction in Chrome. This is the time from hitting a key to the screen being updated. In this example the we're re-rendering a large portion of the screen with new content. There is no network latency involved, we're just updating HTML.
In the below screenshot you can see the Chrome DevTools keydown event, it runs a lot of javascript, and then there's a bunch of painting, compositing etc., and then the keydown event "Response" span ends.
Assuming the horizontal gray lines are vsyncs (does anyone know if these lines are documented anywhere?) where Chrome wrote a new render to the GPU and thus the screen, it seems like the "Response" span the Devtools gives for the keydown event is a good approximation to what I'm trying to measure, as it measures the time from keydown until just after the first grey line after we've finished mutating the DOM.
I've tried various ways to approximate this time in javascript, both using requestAnimationFrame, requestIdleCallback, a setImmediate polyfill with message passing, and a few combinations of the above. It seems like all of them are longer than the pure Javascript time, but mostly they underestimate or overestimate the time to actually update the screen.
Does anyone know of a better way of measuring this time in production? How does the Chrome DevTools metric work? Should I be measuring something else entirely?
...ANSWER
Answered 2017-Nov-30 at 22:42The instrumentation for these Input Latency events is pretty sophisticated and cool. These are great questions.
Input Latency events end time
Input Latency events end around the VSYNC, assuming that the work they triggered caused an invalidation that required a screen update. This is why, in your screenshot, Key Down extends much farther than Key Up. (Even if there were keyup
listeners, they didn't invalidate styles/layout)
It's certainly possible there is an earlier paint & VSYNC that these events terminate at, which isn't really when the screen updates with the response to the input... but you'll have to make that call on your own.
Gray dotted lines, vsync, swap buffers
The gray dotted lines are frame boundaries, but it starts to get tricky here. In Chrome (and AFAIK, other browsers too) there are main thread frames and compositor thread frames. DevTools attempts to display a single timeline of frames to keep things simple, so it can't be perfect. For your purposes, I would look at the right edge of the screenshots in that Frames
track. The right edge is where the screen updated with those contents. On Chrome we call this time swapBuffers
. (VSYNC is technically when the monitor says "I'm ready for a new frame", which is slightly different)
Measuring this in JavaScript
Unfortunately, you don't have the perfect tools to pull this off. The old technique is a double-rAF, and sometimes subtract some time. At this point you definitely know there's been one new frame. Applying some of this knowledge, you could probably be pretty smart. But it wont be perfect. For example, long image decodes will delay the compositor in shipping the frame, but the main thread is now idle and VSYNC will cause it to begin a brand new frame (thus calling rAF again).
The Long Task API could help as it describes what sort of work is taking a while on the main thread. But I don't think it'll have the sort of precision we need to answer these questions. Frame Timing would have, but it died because of privacy reasons.
TDLR:
Use the timestamp from the input event, as it's taken when the input was received at the compositor. And then use some single-rAF, double-rAF mechanism, subtracting some amount of time, to approximate when the frame was shipped. And holler when you have something you're happy with; I'm interested.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install requestidlecallback
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page