How does setTimeout(console.log.bind(console, "something")) work? - javascript

After reading How to hide source of Log messages in Console? , I'm confused about how this command works.
I try to not use setTimeout to wrap it, but the console log always show the source of log messages. Even I try to see the stack trace, it just shows nothing like the second line:
What does the setTimeout(console.log.bind(console, "something")) do?
And it seems cannnot remove setTimeout?
is there any other way to do the same thing?

Let's take it piece-by-piece:
What is console.log.bind(console, "something")?
The Function#bind function creates a new function that, when called, will call the original function using the first argument as this for the call and passing along any further arguments. So console.log.bind(console, "something") creates (but doesn't call) a function that, when it is called, will call console.log with this set to console and passing along "something" as the first argument.
What is setTimeout(x, y)?
It schedules the function x to be called after y milliseconds by the browser; if you don't supply y, it defaults to 0 (call back immediately, as soon as the current code completes).
So taken together, setTimeout(console.log.bind(console, "something")) schedules a call to console.log after a brief delay.
Using the delay means that the call to console.log doesn't happen directly from the code where you do that; the browser calls console.log directly, not within your code. Consequently, the stack trace doesn't show that it happened in your code, because it didn't.

Related

Javascript - Why does a function work on the last call only?

Just started learning how to code. The first lesson taught how functions are used. For the below add function, whenever I call the function more than once, the output is displayed only for the last one. Does a function have to be written separately for each time I call?
function add(first, second) {
return first + second;
}
add(1,2);
add(7,9);
add(3,5);
Output: 8
How can I get an output to all three?
Your add function returns the computation, it does not print anything. So once you call it, all the work will be done and returned, and if you want to see what is returned, all you need is to console them in order to appear in the developer panel
function add(first, second) {
return first + second;
}
console.log(add(1,2)); // <- HERE
console.log(add(7,9);
console.log(add(3,5));
i think you are trying this on developer console. if you run this code as a file, you even doesn't get any output.
The developer console typically logs out the output from the codeblock. once the execution is done.
use console.log() in order to see all outputs.
console.log(add(1,2));
console.log(add(7,9));
console.log(add(3,5));

Determine function file/line location given reference in NodeJS?

The fact that I can't think of how to do this makes me think it's some sort of anti-pattern, or impossible. If anyone has any better ideas of how to handle my situation, recommendations always welcome.
I have a legacy codebase and at one point I am retrieving function references and calling the function. These function calls are expected to return a result, but sometimes they are missing their return statement. Currently I throw an error if the returned value is nullish but this only gives me a stacktrace to the engine location that is calling the function, not the function itself.
Is there any way that I can determine the file name/number of the function, or force the function to throw an error such that a stacktrace to that actual function is generated?
There is no such feature in the Javascript language. It's not anti-pattern, just not something that the language supports. There is no requirement that a function have a return statement and there is no way to force it to throw an exception if it doesn't return a value.
Without seeing any of the relevant code, I can offer some suggestions:
Set a breakpoint at the line of your code that initiates the function call. Then, trace into the function in the debugger. You can go as far into it as you need to and each time you go step into a new function call, it will show you the file and line number that you're on. I use this technique regularly when I'm confused by some behavior by some module (either built-in to nodejs or an external module I'm using) and it's not immediately clear how to find the right code on Github for it. I just step into it and can immediately see the code and watch it execute line by line as needed for whatever problem I'm investigating.
Assuming this function you're calling expects some arguments, you can give it some sort of bogus arguments that would hopefully trigger it to throw some sort of exception and you could then see the stack trace from that exception. For example, if it was expecting a non-optional object as an argument, you could pass null and see if that triggers an exception. If it was expecting a callback, you could pass a non-function and see if that triggered an exception.
As for the name of the function, if the function has an actual name (it's not anonymous) and fn is your function reference, then you can do console.log(fn.name) and see if there is a name. You could also examine fn.toString() and see if it reveals the source code of the function. Sometimes it will and if the function is a named function that may show you its name. This won't show you what file it's in, but you could perhaps then grep for something you see in the source to find it.
Here's an example from point #3:
function hello() {
return "hi";
}
// create function reference that points to my function
const fn = hello;
// log info on that function reference
console.log(fn.name);
console.log(fn.toString());

why is error in Javascript internal/external file stops the below code too?

The Error in JavaScript internal/external file also stops the below code
For example:
var myObj = {};
myObj.other.getName = function(){
console.log('other is not defined');
};
alert('this will not show');
in above code, the alert will not come as the above code has error.
I added the same code in one file tst1.js and below this add one more file tst2.js. put alert('in tst2.js') in it. the tst2 alert come while tst1 not. it is some what related to
code compilation/interpretation.
It's much appreciated If someone explain me this behavior :)
This is the default behaviour of JavaScript. Avoid errors and the code will run normally.
Also you can handle errors with try...catch: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
All JS implementations are, AFAIK, single threaded. This means that all of your code is executed sequentially, on a single thread (logically). If this thread encounters a fatal error, it grinds to a halt. All code that comes after the point where the error occurs is ignored (the JS engine halted, no work is done anymore).
To clarify: it does not matter how many files you have. All of the JS code is stringed together into one big script, and this one script is executed sequentially (execution point starts at line 1 of the first script, and ends at the last line of the last script). Any errors in that code will cause the overall execution to grind to a halt:
//file1.js
var foo = (function()
{
console.log('This file is flawless, but pointless');
}());
//file2.js
foo();//calls previously defined function, assigned to var foo
//file3.js
fudhfsiufhi;//ERROR
//file4.js
foo();//will never get executed, because an error occurred in file3.js
Remove file3, or indeed fix the error, and everything will work as expected.
Allthough JS code is executed/evaluated sequentially, event handlers, callbacks, intervals, and timeouts might lead you to believe otherwise. Couple that with the fact that you have some control over what code is executed when, but not full control, and you get situations that, at first, seem rather counter intuitive. Consider this:
setTimeout(function()
{
massive(syntaxError) -123 + "here";
},0);//zero MS
alert('This will show');
This oddity is well documented, but it has to do with JS having a callback/handler loop, and queue. The setTimeout sets a timeout, to call the anonymous function in 0ms (immediately), but that callback is sent to the queue, which is checked periodically. Before the queue is checked (and the callback invoked), the alert will show. That's why the interval you pass to setTimeout or setInterval is not guaranteed to be exactly N milliseconds.
You can postpone a call to a method somewhat, by adding a call to the queue, like in the snippet above. But when the queue is processed, and what order the queued calls will be performed in are things you have no real say in. No say whatsoever.
It doesn't matter how many files, or how many statements that come before or after the problematic piece of code: there is no thread left to carry on.
The code you posted has a pretty clear error in it: you're assigning a property to other (a property of myObj, but this property is not defined anywhere, let alone defined as an object. Fix it by declaring properties first, before accessing them:
var myObj = {other: {}};//other is an empty object literal
myObj.other.getName = function()
{
console.log('This works');
};
alert('And the alert will show');
Your current code evalutes to:
var myObj = {};//object
var (myObj.other).getName = ...;
//evaluates to undefined
undefined.getName = ...//ERROR
undefined is a primitive value, actually signifying the absence of a value. undefined, therefore, cannot be accessed as an object, it can't be assigned properties.
Note:
This is just for completeness' sake, but JS is indeed single-threaded most of the time, but ECMAScript5 introduced Worker's which allow for some restricted form of multi-threading (without shared state, for example). Read through the MDN documentation on workers if you want to know more.

Problems calling two functions at the same time

I have problems when a I call a function that calls the other function that keep calling back until a puzzle is solved or find no moves.
The thing is that I need to call a function twice but with different values.
I tried storing the values, but as soon as I call the second function wchich calls back, it overrides the values.
the most important pieces of code are here:
function splitways(){
var strsp,aa=dir,bb=xy;
if(nextRock()){
if(xy!=start){
strsp=(aa+""+bb+""+dir+""+xy)*1;
if(!(strsp in arr)){
arr[strsp]=strsp;
caller(dir,xy);
}
}else{
count++;
}
}
}
function caller(num,pos){
var aa=num,bb=pos;
splitways();
//--
dir=aa;
xy=bb;
//--
dir==1?dir=4:dir--;
splitways();
}
Notes, splitways() changes the values of dir and xy, that is why I tried to change them back and then modifing them before the second call to splitways(). But with the first call everything is erased.
I tried everything I can for 2 hours... The best shot I had was to cache them on var aa=num,bb=pos; but that didn't work.
Any ideas are appreciated
Although I'm not entirely sure what you are trying to do with your code, I think you have some of your logic mixed up:
On the first call (I assume you are calling splitways() first), you set "aa=dir" (lets only pay attention to this). When "caller()", it takes the global variable "dir", obviously. Now, in "caller()", you set "aa=num" which translates to "aa=dir". You call splitways again, which then does the exact same thing: "aa=dir". This continues constantly (AKA: until caller() is stopped being called). However, as it goes back through the execution stack, you have, in "caller()", "dir=aa". Now, you already did "aa=num", so "dir=aa" does absolutely nothing since you haven't changed the value of "dir" anywhere that has executed yet.
Eventually, the LATEST "caller()" call will execute the "dir==1?dir=4:dir--" line, but when that function finishes and the execution returns to the SECOND TO LAST "caller()" call, it resets "dir=aa", so dir is never actually changed until the VERY last call (the first "caller()" execution that happened).
If that made absolutely no sense, good. There has got to be a better way for you to do what you are trying to do. Maybe I can help with that?

jQuery callbacks apparently repeat on failure?

I seem to be observing at least one case where a callback function passed to a jQuery effect function will execute repeatedly if there's an error while it's executing.
For example, see this JS Fiddle, featuring the following code:
$('#awesome').fadeOut(400,function () {
log('fading out...');
dieInAFire();
});
log appends whatever's passed to it to a div... but dieInAFire doesn't exist. Rather simply stopping execution, however, the anonymous function appears to be getting called over and over, as evidenced by the growing number of appearances of 'fading out...' in the log div.
Is this the expected behavior? If so, why?
It's a known bug. See the report here.
I just submitted a comment on the bug that patrick dw posted.
Changing the line:
options.complete.call(elem);
To:
setTimeout(function(){
options.complete.call(elem);
}, 0);
Causes the callback to execute asynchronously, and if it will no longer stop execution if it throws any errors. IMO it's better than using a try catch since it doesn't suppress the exception.
If you want to edit your minified version, and you use the latest jQuery, you can search for e.complete.call(d) and replace it with setTimeout(function(){e.complete.call(d)},0)

Categories