Are JavaScript List Operations Synchronous? - javascript

So I've been doing some research into how JavaScript is actually single threaded even though it appears to be multithreaded (or at least that's how I understand it), and I was wondering if the following function would be guaranteed to complete before some other function is called.
I'm fairly certain that it is, but the call to push() makes me worry that when it is called, some other function may execute first. That being said, I can't think of any sort of long running code that would be ran in push().
// adds a new node to children, after checking if its UID is not in childrenAdded
this.addChild = function(newChild) {
if (!_this._childrenAdded[newChild.uid]) {
_this._childrenAdded[newChild.uid] = true;
_this._children.push(newChild);
}
}

All Array methods, including push, are synchronous. That's pretty much the default for all operations in JS, asynchronous is the exception and documented in every such function.

If a function is asynchronous, it will usually take a callback function as parameter, or return a Promise or something of that kind.
That way you'll always be able to make sure, your code executes after the function has terminated, if that is what you want.
So to answer your question: push is synchronous! :)

Everything in Javascript is synchronous. It might behave and look asynchronous, but that's because everything in javascript is put in an execution stack. Once something is finished, it's popped off the stack.
If you have an event, it's pushed into an event loop. Once everything is popped off the execution stack, it searches the event loop to see if it has anything to run. If it does, then it will run that event. It might look asynchronous, but it's really not.
So, in conclusion. Javascript is synchronous.

The Array push method is synchronous. I highly recommend watching this video on the javascript event loop to understand what goes on behind the scenes.
If you watch it enough times, it should clarify how the "single threaded even though it appears to be multithreaded" part of javascript works. Or maybe it might confuse you more, but hey that's javascript for you!

Related

When creating a function to run only one time, should the redefinition happen before or after the function?

I want a function to only run one time. I found this question here on SO and the highest voted examples redefine the function and then execute the code that is supposed to run once. I'm sure there is a good reason for doing that instead of running the code and then redefining the function but I can't figure out what that would be. My first instinct would be to only redefine the function after the code is run since that seems "safer" because the code would have to have run before being redefined.
Can someone explain why convention seems to be to redefine first?
Basically if you want to avoid that the function is "called" twice, disabling the function immediately after the first call is the safest thing to do. When nothing else can happen between the call and the disabler, then nothing unexpected can happen either. If you were to run the code that should be executed only once first, various things might happen:
the code calls the function recursively, or through a callback - you should consider reentrancy
the code does throw an exception
the code returns early
In any of these cases, and possibly more, the disabling code is not reached and a second call could be made.
Notice also that replacing the function is not enough. A caller could easily have created an alias variable that still holds the original function, unaffected by setting some other variable to a noop function. You always need to combine this solution with the "static boolean variable" approach from the accepted answer, unless you control the calling code and know what it does.
Looks like the main reason is for multi-threaded languages. If a function is supposed to run only once and it gets called a second time before the first instance is complete, that would result in being called more than once. Redefining it first means that the function can't run twice.

Javascript async functionality

I have seen a lot of function examples for async javascript containing setTimeout, AJAX calls, etc.
Obviously these all have a certain delay meaning the flow of the script is impacted. But I was wondering, what if I have something like this:
function init() {
this.initSlider();
this.testLog();
}
function initSlider() {
// find multiple items and build up a slider instance
// for each of these elements.
}
function testLog() {
console.log('test);
}
If initSlider possible takes a long time will it simply run my testLog function first?
I am currently a bit unsure about this. I know there might be plenty of examples on the flow of javascript but I can't find ones where a simple function would just take a longer time to run.
It is totally depend on what is there inside initSlider(). Although initslider() is heavy function and do not contain any asynchronus statement
then testLog() will not execute first.
Javascript stores all statements in callstack and they will be executed one after the other.
If there is asynchronus statement then it removes that statement outof the callstack and there is chance of your testLog() to execute.
so for your question my answer will be DEPENDS ON CODE INSIDE initSlider()
Javascript is a technology that runs single threaded. When you use asynchronous methods like AJAX or setTimeout the javascript engine processes those parts one by one (if one is waiting something than switching to another and then back and etc...). You can see the javascript's power on async tasks with Node.js. I guess this blog is very good to understand the Javascript and async methods: click_me!

setTimeout to achieve asynchronicity in Node

What is the point of doing setTimeout(fx, 0) in node?
This is not asynchronous or even non-blocking, as the async function is really the setTimeout, not your fx, and after setTimeout has run asynchronously, you will end up running fx which will block your code anyway.
Doing the setTimeout with 0 to call a function fx will just wait until the stack is empty to run fx, but then while fx is running you won't be able to accept any requests, right?
So is setTimeout(fx, 0) just a way of telling node 'hey, run this whenever you can'? Is there any way to trully run async functions in Node?
If your question is:
Can node run functions in parallel at the same time?
Then the answer is yes, but you have to use a web worker.
The paradigm of asynchronosity in node is different from traditional definitions. The expectation is that you don't run too many ultra-long running functions in node. This way, effective asynchronosity is achieved.
Node is good for some things, not for others, just like any environment.
For a more detailed answer, refer here
As for setTimeout(...,0) calls; sometimes giving a break during a time consuming task to allow calls in the queue have their share of processing can be required. Dividing tasks in different ways can save you from these; but still, this is not really a hack, it is just the way event queues work. Also, using process.nextTick for this aim is much better since when you use setTimeout, calculation and checks of the time passed will be necessary while process.nextTick is simply what we really want: "Hey task, go back to end of the queue, you have used your share!"
If I understand your question correctly the answer would be the following:
As JavaScript is a single threaded language it is still able to deal with two things separately.
Using setTimeout(fx, 0) allows you to push the function or operation within the setTimeout Function in a "waiting qeue". As soon as the Stack of operations is completed the function gets put onto the execution stack and gets executed.
More detailed information about that can be found in this video

Is this recursion or not

function x(){
window.setTimeout(function(){
foo();
if(notDone()){
x();
};
},1000);
}
My concern being unbounded stack growth. I think this is not recursion since the x() call in the timer results in a brand new set of stack frames based on a new dispatch in the JS engine.
But reading the code as an old-fashioned non JS guy it makes me feel uneasy
One extra side question, what happens if I scheduled something (based on math rather than a literal) that resulted in no delay. Would that execute in place or would it be in immediately executed async, or is that implementation defined
It's not - I call it "pseudo-recursion".
The rationale is that it kind of looks like recursion, except that the function always correctly terminates immediately, hence unwinding the stack. It's then the JS event loop that triggers the next invocation.
It is recusive in a sense that it is a function that calls itself but I believe you are right about the stack trace being gone. Under normal execution the stack will just show that it was invoked by setTimeout. The chrome debugger for example will allow you to keep stack traces on async execution, I am not sure how they are doing it but the engine can keep track of the stack somehow.
No matter how the literal is calculated the execution will still be async.
setTimeout(function(){console.log('timeout');}, 0);console.log('executing');
will output:
executing
undefined
timeout
One extra side question, what happens if I scheduled something (based on math rather than a literal) that resulted in no delay. Would that execute in place or would it be in immediately executed async, or is that implementation defined
Still asynchronous. It's just that the timer will be processed immediately once the function returns and the JavaScript engine can process events on the event loop.
Recursion has many different definitions, but if we define it as the willful (as opposed to bug-induced) use of a function that calls itself repeatedly in order to solve a programming problem (which seems to be a common one in a Javascript context), it absolutely is.
The real question is whether or not this could crash the browser. The answer is no in my experience...at least not on Firefox or Chrome. Whether good practice or not, what you've got there is a pretty common Javascript pattern, used in a lot of semi-real-time web applications. Notably, Twitter used to do something very similar to provide users with semi-real-time feed updates (I doubt they still do it now that they're using a Node server).
Also, out of curiously I ran your script with the schedule reset to run every 50ms, and have experienced no slowdowns.

Waiting in JavaScript beyond wrapping everything in setTimeout

So, I'm creating a bot to play a video game online (completely legally, there's a server for bot competitions, don't worry). The code is in JavaScript, which I'm just picking up now, and I'm having trouble telling the bot to do something, then wait either by time or by condition until doing something else.
So far, I'm simply wrapping everything in gigantic setTimeout commands, but this is extremely inelegant.
There's not too much code that's relevant to post, but essentially I've made up a lot of code that does things like move to a specific location, brake, chase another player, etc. Most work with a recursive setTimeout command - press certain buttons, reset variables, then start the function again if the condition isn't met. If I want to move to a specific location then brake when I finish with that, generally I'd put code likes this:
moveTarget(target);
brake();
[...Execute rest of code...]
However, JavaScript executes both of these commands at the same time, which obviously doesn't work very well. Is there a way to make something more like this (Or the equivalent with a condition instead of a specified time):
moveTarget(target);
wait3Seconds();
brake();
[...Execute rest of code...]
Without needing to do this:
moveTarget(target);
setTimeout(function(){
brake();
[...Execute rest of code...]
},3000);
Given how many of these situations I'll have, my code will end up looking like a gigantic mess of nested setTimeouts, which is not very pretty. Is there a better way? I'm already using JQuery, so I'm perfectly willing to use that if necessary.
A little background...
JavaScript does not handle concurrency in the same way as other programming languages you may be used to. Instead, JavaScript has only the one main thread, and instead has a queue for registering then handling events in order as they occur.
For this reason, it is very important to not do things that would block the thread for long periods of time (like a function such as Thread.sleep() would do). That is why you instead should use setTimeout or setInterval for things like this.
You could always create a custom sleep function to write code in the style you are requesting. This might be something like:
function sleep(millis) {
var startTime = Date.now();
while (Date.now() < startTime + millis) {}
}
But this would be VERY, VERY BAD. This would freeze the page while this sleep function is running.
Back to your problem...
You basically need to refactor your code to be more "eventful". Rather than having large, linear chunks of code within the same block, you should write your JavaScript code to use callbacks and timeouts.
So the last code block you showed is really the paradigm you should be following with JavaScript:
moveTarget(target);
setTimeout(function(){
brake();
[...Execute rest of code...]
},3000);
However, you can certainly clean things up a LOT, if instead of [...Execute rest of code...], you split that apart into other functions and call them from within your setTimeout callback. Of course, keeping your code blocks small and concise is a good rule of thumb in any programming language.
You might also interested in checking out the request animation frame function.
There isn't really a better way to do that. The reason is that any sort of waiting is going to trigger a task that goes into the task queue. Since javascript is single threaded, it has to use these task queues and as a result it will just keep on executing instructions past the setTimeout if instructions are present.
In order to execute code after your delay, it has to be in the timeout callback or it will execute immediately.
You could do this if you created all of your methods in a chain that had a wait command, similar to the jQuery queue system.
$("<div>").queue(function(next){
// do a
a();
next();
}).delay(3*1000).queue(function(next){
// after 3 seconds do b
b();
next();
}).delay(3*1000).queue(function(next){
// after 3 more seconds do c
c();
next();
}).dequeue(); //.dequeue() starts it, only has to be called to make a queue that isn't currently running begin.
so all you would have to do is maintain the same chain and keep adding to it.

Categories

Resources