Making a namepaced function asynchronous using setimeout [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have this function which is using namespace. I want to make it asynchronous. Assuming that this function is being called on click of some button ?
var ns = {
somemfunc: function (data) {
alert("hello");
}
}
EDIT - Sorry for being unclear on this. I want to make the call to this function asynchronous by putting the settimeout function inside the somefunc function. Not sure how to do that.
Thanks in advance

You can set this function to be called asynchronously by adding a setTimeout block within the definition of somefunc, note that I am using the term asynchronous loosely here as this function isn't really doing any asynchronous work. An async function would be a function that does some work that takes some time to execute, such as making a network request, aggregating its results and then reporting back to the caller to do some sort of DOM refresh or something, it normally reports back to the caller using a callback, or resolving/rejecting a promise, in the time that this long running code is running, the Event Queue is not blocked and can continue to process other actions if this was not the case then the app would be unresponsive until the long running task finished computing.
What you want to achieve here is not truly async as you're simply scheduling the function to run on the Event Queue in 2 seconds.
var ns = {
somemfunc: function (data) {
setTimeout(function() {
alert("hello");
}, 2000);
}
}
ns.somemfunc();
When ns.somefunc() is called, its now set to execute the function somefunc on the Event Queue in 2000ms (2 seconds). Remember Javascript is single threaded, tasks are scheduled to run on the event queue and will be processed contiguously. If you set the timeout to run the function after 2000ms but the jobs before it take 500ms to compute, then we actually wait 2500ms for the queue to serve that function.

Related

How can i use long callback in javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to make some kind of crawling program. it's chrome extension.
In my program, one function is visit many webpage. This is my plan.
visit page, load page, crawling, visit next page....
I want my program is sequential. but, 'load page' is async. therfore, lower code is not work.
function load_and_download(checked_list) {
for(var item of checked_list){
visit_page(item); //async function
crawl_page(item);
}
}
I found solution like this.
function load_and_download(checked_list, now_index) {
visit_page(checked_list[now_index], function () {//load finish
crawl_page(checked_list[now_index]);
if (checked_list.length > now_index + 1)
load_and_download(checked_list, now_index+1);
})
}
upper code work for me. but, it is recursive function.
if checked_list is very very long, upper code is safe? I know recursive code has stack problem. javascript is safe from that?
What you have here is not a recursive function, if visit_page calls back asynchronously. This pattern is something which I'd like to call pseudorecursion, as due to the async callback, every call to load_and_download will happen in a separate task, thus inside the callstack there will be only one call to that function (per task). Once the async action is scheduled in visit_page, the callstack unwinds again and the next task will be processed. Therefore although it looks like recursion, there's actually no recursion going on.
Here's a simplified example illustrating this:
function asynchronous(callback) {
// Here an asynchronous action gets started and processed somewhere
setTimeout(callback, 1000);
// Execution continues synchronously and the callstack unwinds from here on
}
function pseudoRecursive() {
asynchronous(function () {
console.log("As we're in a new task, the callstack is basically empty:\n", (new Error()).stack);
pseudoRecursive();
});
// Here the callstack unwinds again
}
pseudoRecursive();

is there any difference between a method that takes long time to execute and the setTimeout function?

I am learning javascript. I have a doubt. I heard that when we use the setTimeout method, javascript will remove the callback function of that setTimeout from the call stack and put it on another call stack and continue executing the current call stack.
function f1() {
console.log("print first");
setTimeout(() => {
console.log("print in time out");
}, 4000);
console.log("print last");
}
The output of this function
print first
print last
print in time out
Because the callback of setTimeOut placed into a new stack.
What if I use Ajax request or something like that takes some time to execute without using async. Something like this.
function API(){
const apiCALL = fetch('https://jsonplaceholder.typicode.com/posts');
console.log(apiCALL);
}
is this also put into another call stack?
One thing you have to know it's that both fetch and setTimeout functions are not really a functions of javascript. They belong to Window - Web Apis. You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/Window
And whenever you are using those functions they go of the call stack and into a window api that is written in probably in C# or something. Once they are done doing what they are suppose to do, they send back response inside a callback queue, which u can imagine as a different call stack.
Javascript itself is single threaded but with functions from window api it can be run async.

The difference between using setTimeout(fn, 0) and not using it [duplicate]

This question already has answers here:
Why is setTimeout(fn, 0) sometimes useful?
(19 answers)
Closed 3 years ago.
I have a simple question about setTimeout function
My function:
function myFunc(){
// some code here
}
What's different when
I call a function with and without setTimeout:
myFunc();
setTimeout(function(){
myFunc();
}, 0);
Can someone explain help me? Thank you.
setTimeout waits for a given delay then schedules a new task for its callback. This is why setTimeout is logged after script end, as logging script end is part of the first task, and setTimeout is logged in a separate task. Right, we're almost through this, but I need you to stay strong for this next bit…
Tasks are scheduled so the browser can get from its internals into JavaScript/DOM land and ensures these actions happen sequentially. Between tasks, the browser may render updates. Getting from a mouse click to an event callback requires scheduling a task, as does parsing HTML, and in the above example, setTimeout.
https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
setTimeout(,0) will call after all current queue will be finished, and
normal function call goes in the queue first.
You can see here:
function myFunc1(){
console.log("In myFunc1");
}
function myFunc2(){
console.log("In myFunc2");
}
setTimeout(function(){
myFunc1();
}, 0);
myFunc2();

Javascript Asynchronous with setTimeout(..., 0)

I wanted to have a better understanding of how the event loop and asynchronous code works in Javascript. There is a ton of resources online but I could not find an answer to my question
Everyday I mostly use callbacks, promises, async/awaits, but at the end I am simply relying on already asynchronous methods.
Therefore I wanted to know how it works, creating an async function from scratch, and deal with blocking code (or should I say slow code, that is not an HttpRequest or anything that is already provided to us).
For example taking while loop with a very high condition to stop it, should take a second to finish. And this is what I decided to implement for my tests.
After my research, I could read that one way of making my code asynchronous, would be to use setTimeout with a 0ms delay (placing a message in the event queue, that will be executed after the next tick)
function longOperation(cb) {
setTimeout(function() {
var i = 0;
while (i != 1000000000) { i++; }
cb();
}, 0);
}
longOperation(() => {
console.log('callback finished');
})
console.log('start');
My question is:
When my code is finally going to be executed, why isn't it blocking anymore ? What is the difference between executing it normally, and placing a message that the event loop will pick to push it to the call stack ?
The following video shows how the event loop handles a setTimeout with 0 delay.
JavaScript Event loop with setTimeout 0
However, the code executed is a simple console log. In my example, this is a "long" operation...
The outer code executes to completion.
The setTimeout 0 timer expires immediately, so its callback runs right away and executes to completion (the long-running while loop and its callback).
During both of these code execution phases, no other JavaScript user code will run.

Is there any possibility of two asynchronous Javascript function instances executing two blocks of code at the same time?

I understand that Javascript doesn't have multiple threads, but I'd like to know if the following code has any chance of breaking. My understanding is that unless an asynchronous function is called, such as setTimeout or an AJAX call, that once a block of code starts executing there's no way for it to pause until it completes or does call an asynchronous function.
Basically, users select multiple checkboxes and then hits a button that executes AJAX processing of their selections. My goal is to have a "Saving..." icon that stays only until all the AJAX processes are complete, and after all are finished display a success message.
Barring any AJAX errors, so long as the callback function in the jQuery.post executes in its entirety without interruption, I don't see how the if(numProcessed == toProcess) would ever execute more than once or less than once. But if two AJAX callbacks get into the callback function, both increment the numProcessed counter before either get to the following if, then it seems that the code inside would be executed twice.
var numProcessed = 0;
var checkedBoxes = jQuery("input[type=checkbox]:checked");
var toProcess = checkedBoxes.size();
checkedBoxes.each(function() {
jQuery.post('somepage.php',{...},function(results) {
numProcessed++;
if(numProcessed == toProcess) {
jQuery("#saving-message").remove();
jQuery("#feedback-panel").text('Successfully processed all selections.');
}
}
}
There is only one thread in JavaScript so every function that want to be execute is put in stack and have to wait until all others are execute. In your case "each" is the first function in the stack, so every callback function have to wait and will be execute in the order they put on the stack.
After all "numProcessed == toProcess" could only one time be true.
The rx.net team has introduced rx for javascript. Reactive extension are for asynchronous programming. they have also written for rxjs for jquery too. My be that suite your need http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx

Categories

Resources