setTimeout not the same as this.async? - polymer

Sometimes I'm coding in a wrong way my polymer 1.0 web app and stuff stops to work properly. Like setting data to some custom element and then immediately trying to read some data out of it (that depends on the data just set) (because I don't know better). Sometimes this doesn't work. Most of the time this.async will help me out, but sometimes it will not. However, setTimeout has never ever failed me in these kind of situations. Most of the time calling setTimeout without providing wait time will work just as well.
For a long time I thought that this.async(function(){...}) is the same as setTimeout(function(){...}). Because sometimes code inside this.async will fail to see changes in custom element's data while code inside setTimeout will not.
Are these two methods are implemented in different way?

this.async adds your function to the start of the event queue, while setTimeout adds it to the end. If you use setTimeout other functions may have been executed before your function is called, causing the changes that you can see in your data.
From the documentation of this.async:
If no wait time is specified, runs tasks with microtask timing (after the current method finishes, but before the next event from the event queue is processed)
setTimeout on the other hand will add your function to the end of the queue as is described in the section "Adding Messages" of this article.
Calling setTimeout will add a message to the queue after the time passed as second argument. If there is no other message in the queue, the message is processed right away; however, if there are messages, the setTimeout message will have to wait for other messages to be processed. For that reason the second argument indicates a minimum time and not a guaranteed time

Related

SolidJS: "computations created outside a `createRoot` or `render` will never be disposed" messages in the console log

When working on a SolidJS project you might start seeing the following warning message in your JS console:
computations created outside a `createRoot` or `render` will never be disposed
There are some information available on this in SolidJS' Github repository issues. But after reading them I was still not quite sure what this was all about and whether my code was really doing something wrong.
I managed to track down where it came from and find a fix for it based on the documentation. So I'm providing the explanation and the solution for those Googling this warning message.
In essence this is a warning about a possibility of a memory leak due to a reactive computation being created without the proper context which would dispose of it when no longer needed.
A proper context is created a couple of different ways. Here are the ones I know about:
By using the render function.
By using the createRoot function. Under the hood render uses this.
By using the createContext function.
The first is by far the most common way, because each app has at least one render function call to get the whole show started.
So what makes the code go "out of context"?
Probably the most common way is via async calls. The context creation with its dependency tree happens only when the synchronous portion of the code finishes running. This includes all the export default function in your modules and the main app function.
But code that runs at a later time because of a setTimeout or by being in an async function will be outside of this context and any reactive computations created will not be tracked and might stick around without being garbage collected.
An example
Let's say you have a data input screen and have a Save button on it that makes an API call to your server to save the data. And you want to provide a feedback to the user whether the operation succeeded or not, with a nice HTML formatted message.
[msg,setMsg] = createSignal(<></>)
async function saveForm(){
...
setMsg(<p>Saving your data.<i>Please stand by...</i></p>)
const result=await callApi('updateUser',formData)
if(result.ok){
setMsg(<p>Your changes were <b>successfully</b> saved!</p> )
} else {
setMsg(<p>There was a problem saving your data! <br>Error: </p><pre>{result.error}</pre> )
}
}
...
<div>
...
<button onClick={saveForm} >Save</button>
{msg()}
</div>
This will produce the above mentioned warning when the API call returns an error, but not the other times. Why?
The reason for this is that SolidJS considers the code inserts inside JSX to be reactive, ie: need to be watched and re-evaluated. So inserting the error message from the API call creates a reactive computation.
The solution
I found the solution at the very end of the SolidJS doc. It's a special JSX modifier: /*#once*/
It can be used at the beginning of a curly brace expression and it tells the SolidJS compiler to explicitly not to make this a reactive expression. In other words: it will evaluated once and only once when the DOM nodes are created from the JSX.
In the above example here's how to use it:
setMsg(<p>There was a problem saving your data! <br>Error: </p><pre>{/*#once*/ result.error}</pre> )
After this there will be no more warning messages :)
In my case, I had an input and when that input changed I re-created an SVG drawing. Because the SVG creation was an expensive operation, I added a debounce in the createEffect function which ran when the input changed. debounce is a technique to defer the processing until the input stops changing for at least X amount of time. It involved running the SVG generation code inside the setTimeout function, thus being outside of the main context. Using the /*#once*/ modifier everywhere where I inserted an expression in the generated JSX has fixed the problem.

How can I unset a CUDA event?

I have a processing loop on the host, where I record an event in a GPU stream. Then another stream waits for that event (waits for event's state "set" or "true"). Will this function (cudaStreamWaitEvent) unset this event (so, switching it to "unset" or "false")? If not, what CUDA function I can use to unset this event?
This sounds very much like an XY question. You might be better off describing at a higher level what it is you are trying to accomplish, or what problem you are facing or think you are facing.
cudaStreamWaitEvent does not "unset" an event.
When the event is encountered in the stream, then cudaStreamWaitEvent will unblock, and any subsequent calls to cudaStreamWaitEvent on the same event will immediately unblock (assuming no cudaEventRecord has again been issued for that event). This behavior is easy to prove with a trivial code sample.
The function that "unsets" a cudaEvent is cudaEventRecord(). Any cudaStreamWaitEvent calls issued after that event gets recorded will wait again, until it is encountered again.
You may want to read the runtime API documentation for cudaEventRecord and cudaStreamWaitEvent. Note the following excerpts:
cudaEventRecord:
If cudaEventRecord() has previously been called on event, then this call will overwrite any existing state in event. Any subsequent calls which examine the status of event will only examine the completion of this most recent call to cudaEventRecord().
cudaStreamWaitEvent:
The stream stream will wait only for the completion of the most recent host call to cudaEventRecord() on event.

Polymer: when to use async?

What's the purpose of async method in polymer? When should I use it?
Right now I'm using it like hm-this-bug-is-kinda-weird-maybe-async-will-fix-it-yep-id-did-yey. It does not give me any confidence in my code as I'm sprinkling async just when some timing bug shows up.
The answer is slightly different here depending on whether you're using Polymer 0.5 or 1.0. In 1.0, more operations are synchronous, so you may not see quite as much need for async (also, the async method works slightly differently in 1.0).
Let's start with 0.5. Most of the cases have to do with the effects of changing properties. Properties used in data bindings or observers are observed for changes. When you change one of these
properties, any side-effects of that change take place asynchronously, with microtask timing. That means that the work happens after the current event handler returns, but before the next event is processed.
In other words, if I have a data binding like this:
<div id="output">{{someProperty}}</div>
Suppose I have the following code:
this.someProperty = "New Value";
console.log(this.$.output.textContent); // logs "Old Value"
This is where the asynchrony bites you. If you want the bound data to be updated, you need to give the data binding system a chance to work. If you move that console.log statement into an async, so it's executed at a later time, you get the response you expect:
this.async(function() {
console.log(this.$.output.textContent); // logs "New Value"
});
Most of the time, you don't need to poke at data bound DOM elements. But in the event that you do, or that you're waiting on the side effect of an observer, you probably want an async.
In Polymer 1.0, data binding and single-property observers are synchronous. Multi-property observers and some DOM operations are async.
(While the APIs are different from JavaScript, this Dart article about the event loop is the best one I've found to describe the event loop and microtask queue: https://www.dartlang.org/articles/event-loop/)

ProcessEvents not on the main thread for WinRT

I want to set a timer that emulates a thread that every few milliseconds, calls Dispatcher->ProcessEvents() while inside the main run loop, I'm just rendering and presenting.
In this article, http://msdn.microsoft.com/en-us/library/windows/apps/hh994934.aspx, and near the bottom, it says, "As noted previously, you can also do this with a timer object that you have synchronized to the display device's refresh signal." I'm assuming this can be done since Microsoft has explicitly stated that it could be done.
However, when I attempt this method, if I cache the dispatcher and call dispatcher->ProcessEvents() from inside a periodic ThreadPoolTimer, the events don't get processed.
Any ideas?

Is Event TIMER always dispatched before TIMER_COMPLETE?

Is flash.utils.Timer object's event TIMER always dispatched before TIMER_COMPLETE?
During the 2nd event, I am nullifying stuff that are required during the 1st event; so their order is of prime importance. I checked the docs and there is no guarantee for their dispatching order.
In tests I've done it seems that this is the case, but I don't want to distribute publicly software without confirming first.
You can avoid this problem by using TimerEvent.TIMER only:
private function onTimer(event:TimerEvent)
{
// ...
if (timer.currentCount == timer.repeatCount) {
// timer is complete
}
}
I'm almost positive this is the case, since the code seems to be in the player itself I don't think you can get at the source to get a legitimate confirmation, however I have always seen this to be the case myself and from how the docs read it sounds as though a TIMER event would always be dispatched before the complete event
timerComplete
Dispatched whenever it has completed the number of requests set by Timer.repeatCount.
timer
Dispatched whenever a Timer object reaches an interval specified according to the Timer.delay property.
So I imagine the timerComplete is dispatched after it receives enough timer events that the currentCount equals the repeat count then a timerComplete is dispatched, however without being able to look at the code it's impossible for anyone to completely confirm this. Possibly you could look at the Gnash source to see how it's handled by that implementation of the player, but it's not necessarily the same in the normal Flash Player.