What happens if call two functions when button click event in javaScript - javascript

I'm tying to call two functions in JavaScript when a button click event happens.
<button type="submit" id="mySubmit" onClick="submitInput();getAll()">Search</button>
So I wondered what function will call first. And I have no idea.
Will the submitInput() executes first or getAll() or both executes at the same time concurrently. ?

It executes the same way as ordinary javascript. submitInput() executes first. I would not reccomend doing it this way though. It would be considered bad practice. keep your javascript out of your HTML ok.
Lastly, just because something executes first, does not mean that it will finish first.. javascript is both async and synchronous in some cases.

JavaScript is by nature mono-thread, that is to say its engine can only compute one operation at once (it is not parallel !). It means that as long as a process is not finished, the user remains stuck in front of his browser and has to wait till the end. Theoritically :)
Fortunately, JS is also asynchronous, it means that one is able to free the user thread, waiting for some other conditions to be fullfilled to continue the computation. To be more accurate, the execution of some functions can be delayed, one of the simplest examples is the use of the functions setTimeout() (once) or setInterval() (several times). A callback is a function triggered only under some conditions (i.e. a time interval expires, a script sends an answer, etc...). It prevents the browser from being "freezed", waiting for the result of a computation.
In your case, if there isn't any asynchronous call, the functions will be executed in the order you gave. Once the first is completed, the second will be triggered.
Try those two dummy functions :
function myFunction() {
for (var iter = 0; iter < 500000000; iter++) {
if (iter==499999999) {alert ("done !");}
}
}
function myFunction2() {
alert ("Hi there !");
}
Call them in this order, then change their order. The second will always be executed once the first is complete.

Related

Javascript asynchronous nature

I was recently tinkering with node js and its asynchronous nature and came across something weird. Here is the code -
let sum = 0;
for(let i=0;i<10000000000;i++){
sum += i
if(i==99999999){
console.log(sum);
}
}
console.log('abc');
By definition of non blocking,it should not wait for the for loop results and should print 'abc' first and then print the value of sum after completion of calculation right? However,this is not happening and the program is waiting for the for loop to finish and print the value of sum and then print 'abc'. Could anyone explain the reasoning behind this? Is this happening due to the way console.log works?
Its non blocking for IO operations, IO operations include file read write, network read write, database read write etc.
This is controlled by event loop.
For loop is not IO operation, however if you have IO operation inside for loop you will get the non blocking taste.
You can read more here https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/
Javascript works synchronouse. There are few things that work asynchronouse:
setImmediate, setTimeout(), and promises like fetch(), Promise.resolve() etc.
I also need to mention that the callback from the setTimeout for example is getting added to an task que or also named "callback que" and its waiting till the event loop is done with its synchronouse code. After the event loop is ready it will take this callback and add it to the callstack and execute that callback function. And this code will be executed synchronouse.
There is actually no true parallelism. For that you should use web workers.

Why does the setTimeout callback wait for the end of the loop when the timer is 0ms?

The thing I don't understand about closures is the fact that the setTimeout callbacks don't fire until the loop has finished. It looks to me that clearly the function is being executed during each iteration.
I am not concerned why they are all "6"'s I understand that part. I just need an explanation as to why it waits till the loop has to finish before they actually run.
for (var i = 1; i <= 5; i++)
{
setTimeout(function timer()
{
console.log(i);
}, 0);
}
The setTimeouts are queued to start running at the end of the current event loop. So, the setTimeouts can fire much later than the end of the for loop.
MDN has a great description about the event loop with regard to setTimeout:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop
Specifically this part:
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.
JavaScript runs with a single event loop.
The event loop is busy running the function that is calling setTimeout so it isn't looking to see if any events are on the timeout queue waiting to run.
Even if that wasn't the case, most JS implementations implement a minimum timeout (see Minimum delay and timeout nesting) value and raise whatever you pass (0) to it if it falls below that value.

What is this timeout-related feature of javascript called?

I'm familiar with this behavior, but don't have the vocabulary to describe (and thus google) it.
setTimeout(function () { alert("timeout!"); }, 1000);
veryLongProcess(); // lasts longer than 1000 milliseconds
I believe the result of this is that you get your alert after the long process is finished, i.e. longer than 1 second after the code was executed. I imagine this as timeouts sending functions to some separate "thread" or "stack" or "cycle" that can only start after the current one is finished, even if that current one takes longer than the timeout was originally specified for.
Is there a name for this? How can I learn more about how it works?
I believe you may be looking for the term 'synchronous' programming.
Since JavaScript is single threaded, your veryLongProcess() will in fact cause the alert to trigger after 1000ms because of something called blocking.
Be aware that blocking JavaScript can degrade the user experience significantly, such as locking up the browser, or causing it to show a 'kill script' dialog, breaking the functionality of your process.
What you're looking for is called "callback functions." You can pass functions as a variables to other functions, and then execute them whenever you want. I wrote a quick sample for how it works below (untested).
function longProcess(callback){
//a bunch of code execution goes here
var testNumber = 5;
//This portion of code happens after all desired code is run
if (callback != undefined){ //Check to see if a variable 'callback' was passed... we're assuming it's a function
callback(testNumber); //Execute the callback, passing it a value
}
}
function testCallback(number){
alert("Number: " + number); //Alert box will popup with "Number: 5"
}
longProcess(testCallback); //Call your long process, passing another function as a variable

making asynchronous calls with jquery

I have a function called checkStatus(x) where x is Id. How can I call this function n times asynchronously ? Without being dependent one on another to completed and for another to start?
I'm using jquery
EDIT:
I'm not sure if I used the correct term, but here is what I want. I have a list of ID's and I iterate trough a list, I want to execute this function for each ID.
But I don't want to wait for one id to finnish, and then to execute this function on another id. Is it possible to execute this function at the same time?
Javascript engines are single-threaded, meaning that only one piece of code is ever executing at once. Asynchronous features (AJAX, timeouts/intervals) cause different blocks of code to run in sequence, not in parallel (i.e. you'll never get any use out of multiple processor cores in Javascript).
The simplest way to produce asynchronous (non-blocking) code is using setTimeout (I strongly discourage using setInterval), as others have suggested, but there is no performance benefit to doing so. This simply ensures that your browser won't "hang" during slow JS computations, by allowing the browser's other tasks (such as page repainting and user input) the opportunity to run. It won't actually increase the speed of those computations (in fact, it slightly slows them, due to the small additional overhead of the timeouts).
It is possible to create separate threads in Javascript using web workers, but their capabilities are limited (for example, they cannot alter the DOM) and they are not yet supported by IE.
An example of a long-running, non-blocking task using "recursive" setTimeout calls:
function getStarted(elements) {
// this function must be inside the outer function
// so that `i` (below) can be accessed via a closure
function processElement() {
// do work on elements[i] here
// or pass it to another function
// this continues only if we haven't hit the end of the array,
// like the second and third clauses of a `for` loop
if (++i < elements.length) {
setTimeout(processElement, 0);
}
}
// don't bother with empty arrays
if (elements.length) {
// the same `i` is used each time processElement runs
// and acts just like a `for` loop index
var i = 0;
// optional: make a copy of the array so that it
// doesn't get modified while we're working
elements = elements.slice();
// even a zero-millisecond "delay" gives the browser the
// opportunity to run other code
setTimeout(processElement, 0);
}
}
Use the setTimeout or setInterval functions.
setTimeout(function(){checkStatus(x);}, 100);
setTimeout(function(){checkStatus(x);}, 200);
setTimeout(function(){checkStatus(x);}, 300);

Javascript Anonymous Functions and Global Variables

I thought I would try and be clever and create a Wait function of my own (I realise there are other ways to do this). So I wrote:
var interval_id;
var countdowntimer = 0;
function Wait(wait_interval) {
countdowntimer = wait_interval;
interval_id = setInterval(function() {
--countdowntimer <=0 ? clearInterval(interval_id) : null;
}, 1000);
do {} while (countdowntimer >= 0);
}
// Wait a bit: 5 secs
Wait(5);
This all works, except for the infinite looping. Upon inspection, if I take the While loop out, the anonymous function is entered 5 times, as expected. So clearly the global variable countdowntimer is decremented.
However, if I check the value of countdowntimer, in the While loop, it never goes down. This is despite the fact that the anonymous function is being called whilst in the While loop!
Clearly, somehow, there are two values of countdowntimer floating around, but why?
EDIT
Ok, so I understand (now) that Javascript is single threaded. And that - sort of - answers my question. But, at which point in the processing of this single thread, does the so called asynchronous call using setInterval actually happen? Is it just between function calls? Surely not, what about functions that take a long time to execute?
There aren't two copies of the variable lying around. Javascript in web browsers is single threaded (unless you use the new web workers stuff). So the anonymous function never has the chance to run, because Wait is tying up the interpreter.
You can't use a busy-wait functions in browser-based Javascript; nothing else will ever happen (and they're a bad idea in most other environments, even where they're possible). You have to use callbacks instead. Here's a minimalist reworking of that:
var interval_id;
var countdowntimer = 0;
function Wait(wait_interval, callback) {
countdowntimer = wait_interval;
interval_id = setInterval(function() {
if (--countdowntimer <=0) {
clearInterval(interval_id);
interval_id = 0;
callback();
}
}, 1000);
}
// Wait a bit: 5 secs
Wait(5, function() {
alert("Done waiting");
});
// Any code here happens immediately, it doesn't wait for the callback
Edit Answering your follow-up:
But, at which point in the processing of this single thread, does the so called asynchronous call using setInterval actually happen? Is it just between function calls? Surely not, what about functions that take a long time to execute?
Pretty much, yeah — and so it's important that functions not be long-running. (Technically it's not even between function calls, in that if you have a function that calls three other functions, the interpreter can't do anything else while that (outer) function is running.) The interpreter essentially maintains a queue of functions it needs to execute. It starts starts by executing any global code (rather like a big function call). Then, when things happen (user input events, the time to call a callback scheduled via setTimeout is reached, etc.), the interpreter pushes the calls it needs to make onto the queue. It always processes the call at the front of the queue, and so things can stack up (like your setInterval calls, although setInterval is a bit special — it won't queue a subsequent callback if a previous one is still sitting in the queue waiting to be processed). So think in terms of when your code gets control and when it releases control (e.g., by returning). The interpreter can only do other things after you release control and before it gives it back to you again. And again, on some browsers (IE, for instance), that same thread is also used for painting the UI and such, so DOM insertions (for instance) won't show up until you release control back to the browser so it can get on with doing its painting.
When Javascript in web browsers, you really need to take an event-driven approach to designing and coding your solutions. The classic example is prompting the user for information. In a non-event-driven world, you could do this:
// Non-functional non-event-driven pseudo-example
askTheQuestion();
answer = readTheAnswer(); // Script pauses here
doSomethingWithAnswer(answer); // This doesn't happen until we have an answer
doSomethingElse();
That doesn't work in an event-driven world. Instead, you do this:
askTheQuestion();
setCallbackForQuestionAnsweredEvent(doSomethingWithAnswer);
// If we had code here, it would happen *immediately*,
// it wouldn't wait for the answer
So for instance, askTheQuestion might overlay a div on the page with fields prompting the user for various pieces of information with an "OK" button for them to click when they're done. setCallbackForQuestionAnswered would really be hooking the click event on the "OK" button. doSomethingWithAnswer would collect the information from the fields, remove or hide the div, and do something with the info.
Most Javascript implementation are single threaded, so when it is executing the while loop, it doesn't let anything else execute, so the interval never runs while the while is running, thus making an infinite loop.
There are many similar attempts to create a sleep/wait/pause function in javascript, but since most implementations are single threaded, it simply doesn't let you do anything else while sleeping(!).
The alternative way to make a delay is to write timeouts. They can postpone an execution of a chunk of code, but you have to break it in many functions. You can always inline functions so it makes it easier to follow (and to share variables within the same execution context).
There are also some libraries that adds some syntatic suggar to javascript making this more readable.
EDIT:
There's an excelent blog post by John Resig himself about How javascript timers work. He pretty much explains it in details. Hope it helps.
Actually, its pretty much guaranteed that the interval function will never run while the loop does as javascript is single-threaded.
There is a reason why no-one has made Wait before (and so many have tried); it simply cannot be done.
You will have to resort to braking up your function into bits and schedule these using setTimeout or setInterval.
//first part
...
setTimeout(function(){
//next part
}, 5000/*ms*/);
Depending on your needs this could (should) be implemented as a state machine.
Instead of using a global countdowntimer variable, why not just change the millisecond attribute on setInterval instead? Something like:
var waitId;
function Wait(waitSeconds)
{
waitId= setInterval(function(){clearInterval(waitId);}, waitSeconds * 1000);
}

Categories