Executing code after manually firing an event - javascript

I'm manually creating and dispatching events to the DOM via createEvent and dispatchEvent...
it seems to work fine.
However, I'm firing multiple events and I need code to execute between them.
If I understand correctly (my background is in server programming), browsers place the event in a queue, which then executes in a background thread.
so if I do work in the foreground I could complete BEFORE the event executes.
Which I think I'm seeing.
.. so my work around is to dispatchEvent... then place a new function via setTimeout(callback,0) ...
the callback in timeout should execute AFTER the event.. correct?
Then I can just make my whole algorithm use callbacks.
do I have this right?

Related

Throttling events - Perfomance implications of adding and removing event listeners

This isn't a problem I'm having - it's more just a general interest query.
I've just implemented throttling on scroll events on my web app. I've done it in the way all tutorials teach you i.e. inside your function, you block the rest of its execution using some timer controlled variable which makes you wait until the function can be run again.
My question is this: surely in this case, on every scroll event, the function is still being run, it's just that the function is quickly exited so it doesn't take much of a performance hit.
I'm surprised that the standard correct way to throttle events isn't something like:
Add an event listener that runs a function.
When event occurs, run the function, remove the event listener and then set up a timeout to re-add the event listener at a later time.
I presume people far cleverer than me have thought of this and there are good reasons why not to do this.
Is it because it's unnecessarily fiddly? Is it much more processor intensive to add and remove listeners than it is to run empty functions?
I'm just curious. Thanks.
Neither of those is a performance concern. Starting to run a function and then bailing out is very cheap, and so too is adding/removing event listeners. So if you have a situation that can be solved by adding and removing event listeners, and it's easier to under than the other options, feel free to do it.
I can think of a couple reasons why i wouldn't do it though
It's narrow. There are very few problems that can be solved by removing an event listener. Throttling, yes, but even a very similar feature -- debouncing -- can't be done by removing the event listener. (Debouncing means to wait until there's a period of inactivity. So if the function keeps getting called quickly, you'll keep delaying longer. If you remove the event listener, you lose the ability to know that you need to wait longer)
You have to know how to tear down and set up the event listener. For your case that may be fine, but a general-purpose throttle utility (Eg, lodash's throttle function) may have no idea how the function is going to be called. If you use the setTimeout approach instead, then it will work regardless of how it's being called.

How Javascript control events

Let's say I have a simple code using onmouseover event
<div onmousemove="myMoveFunction()">
<p id="demo">I will demonstrate onmousemove!</p>
</div>
(from w3school)
I want to ask that, how does Javascript know mouse is on that div? Or when we use onclick, how does Js know button has been clicked. Is there automatic event listeners? or Is there any cycle controlling changes for events continually in the background?
Please help me I'm confused.
Any links to read would be okay too
A browser is responsible for gathering events as they appear on the page. When there's an event listener added for a given action, the listener's callback is added to the event loop. Event loop is an infinite loop that constantly checks if there's something to do (in a cpu optimized manner). On event loop there are two main tasks:
rendering the page if there's a change in DOM or CSSOM
executing callbacks when some specific action happens
It is important to know that javascript is single threaded, meaning if there's a long running callback, the browser won't be able to rerender the page so the page just freezes.
Another way to understand what's happening under the hood is to open chrome dev tools and go to performance panel. You can find there exactly what happens when you interact with the page:
There are a few ways to add an event listener:
in html using on[eventname]=action, i.e. <div onmousemove="myMoveFunction()">
in javascript by assigning a function to on[eventname] property, i.e. windows.onload = () => alert("hello");
in javascript by using addEventListener() method, i.e. element.addEventListener("click", () => alert("hello"));
If you want to know more about event loop, here are good resources:
Philip Roberts: What the heck is the event loop anyway?
Jake Archibald on ‘The Event Loop’ (more advanced)
There's also pretty good and free course that explains a lot about how browser works and most importantly shows you how to improve site's performance:
Browser Rendering Optimization
When you use e.g. <div onmousemove="myMoveFunction()">, as the browser reads the DOM on page load, behind the scenes it generates code for the event listener and there is not much else to it.

Javascript events using H.datalens.Provider

Are there any events to subscribe to using
H.datalens.Provider
? So one can know when all data has been loaded for example, or if there was an error.
I'm afraid not. There is an "update" event being triggered when the data gets updated (see https://developer.here.com/documentation/geovisualization/datalens/h-datalens-provider.html) but I do recall it triggering multiple times. Afaik there's no easy way to know the data has finished loading.
A trick I've seen using is listening to the event and starting a timeout, resetting it every time a new update event gets triggered. When the timeout is finally able to execute, the updates are over. This is not by any means a good solution, but might be of help.

Does the HTML DOMs have any effect on one another when run simultaneously?

I want to know if the DOM elements have any effect on one another if one doesn't stop loading before another command is executed. For example; an onload event is still loading but the user happened to scroll before it stops, triggering an onscroll event.
Is this possible; if yes then how to stop it?
Aside from things like Web Workers, generally JavaScript in the browser is single-threaded. Only one event handler will run at a time.

Detect if an Input has Changed dynamically

Other javascript is changing the value of an input and I was wondering if there was a way to detect the change.
This question has nothing to do with Keyup or Change. This is not being typed in by the user it is being changed by other javascript though various actions of the user.
When changing an event programatically, you can trigger a change event to make sure event handlers that are attached to the element are fired. jQuery has a trigger() method to do this:
$('#elementID').on('change', function() {
alert( this.value );
});
$('#elementID').val('some new value').trigger('change');
The quick run-down of what I am going to say is: there is no way other than to modify the third-party scripts to output stuff, or to use setInterval (costly).
The bottom line of this issue is a simple one, that does not appear to be so at first: How can you get your scrips to communicate with each other?
When a script modifies the value of an input through JS methods (i.e. not user input), they have to go through specific hoops to get the "change" event to fire (they can fire it manually by calling it, which most devs never do and is easily forgotten when writing code). In practice, people tend to rely on the observation events (user-defined ones) to track code changes. This is very similar to DOM events - you bind callbacks to your script, which allow you to tap callbacks in that will fire whenever your scripts do something interesting (like modifying inputs. This is just one example). You then teach your scripts and developers to fire events on useful stuff using the callbacks to notify other scripts.
A great library for this is Postal, which is originally a Node library. jQuery also has an event system you can tap into. However, if you want to roll your own, all you have to read into is the Observer design pattern. It is trivial: you bind a function to your object to pick up callbacks, and another to fire them. Whenever you change the thing, you fire the callback. Simples.
Failure to do so means setInterval. Sucks, but there you go :-(

Categories