I hit the dead end with this one, scratching my head for half a day already. The problem is quite strange, if you'd care to look at my source code: www.modwebsolutions.com/test2 (warning: not optimized yet, might lock browser for a few seconds). Problem is, that sequence of setTimeouts works ok in Opera, but in other browsers only first one is executed and then execution of the script stops. Exerpt from my code:
var a1=setTimeout(drawVertical([arguments]),1000);
var b1=setTimeout(drawVertical([arguments]),1000);
var c1=setTimeout(drawVertical([arguments]),1000);
var d1=setTimeout(drawVertical([arguments)],1000);
Tried everything, enclosing function in quotes, looking for other syntax errors, nothing helped. And the strange thing is as I mentioned - everything works ok in Opera.
UPDATE: also works in Chrome, and that makes it even more confusing...
UPDATE2: same example without timeout, works just fine (though slow): www.modwebsolutions.com/test
You should pass the parameters for you function after the function and timeout. Have a look at the documentation
var a1 = setTimeout(drawVertical, 1000, [arguments]);
What you have done here is called a function before setting the timeout. Immediately when the code sees drawVertical([arguments]), it is going to call that function. The return value of that function is what you are passing as your first argument into setTimeout, so unless drawVertical returns a function, this won't work.
So you could get this to work by giving setTimeout a function to call:
var args = arguments;
var a1=setTimeout(function() { drawVertical([args]); },1000);
...
EDIT: I set the outer arguments to an args variable, since the arguments would be different in the inner function.
Related
I want to modify the output of the functions (just say RANDOM examples, apologies for any code mistakes):
ng-if=!pfile.isgame
ng-if=! pfile.examplefile
-from false to true before it even has the page has any chance to drop any code on the page. How can I make it so I can append code to the page to the very beginning of the page to force every output of these particular functions to go true, on a live page?
This is definitely possible, I'm not sure where the function would be however the elements you can actually see the arguments on the page and it doesn't not look server sided at all, its just how its done. I read many articles but it many of them have not really helped me.
I am aware of Event Listener Breakpoints, its just the problem if I'm choosing the right one.
Thank you and I really appreciate it just if you can please dum down the explanation for me as even though I do understand HTML and JavaScript to an OK standard, I am still a massive beginner. This is something I always wanted to try out.
Hopefully I have understood your question correctly. There are a couple of options and the answer will depend on whether the functions are declarations or expressions.
If they are declarations, they get hoisted to the top on first pass, so that by the time your code begins execution, the function already exists and you can overwrite it early on.
If it's a function expression, you have to wait until the function expression has been created.
Example 1 (Function Declaration):
I have a function declaration on my page, which returns true if there is a remainder in the calculation, otherwise false. I execute it on page load. The output is false here:
function hasRemainder(first, second) {
return (first % second != 0);
}
console.log(hasRemainder(10, 5));
false
I have now added the Script First Statement breakpoint in DevTools, so that the debugger breaks before any script is run:
I re-open the page and the execution pauses. I now run the following code in the Console tab to override the hasRemainder function so that it always returns true:
hasRemainder = function() {
return true;
}
Finally, I click Play to continue execution. You can long click to select Long Resume, which skips breakpoints for 500ms so that you don't get caught for very single breakpoint thereafter.
true
The output this time is true as you would expect.
Example 2 (Function Expression):
We can't rely on the early breakpoint this time because the function won't exist yet. We need to add the breakpoint just after the function expression has been created.
Search for the functions using Cmd+Opt+F (Mac) or Ctrl+Shift+F (Windows).
When you are in the file with the function expression, put a breakpoint at the end of the function. When the debugger pauses, run the overriding function into the Console, and then press play to continue execution.
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.
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)
OK, I looked a lot for this on the web but cannot find an answer.
I can expect CSS differences between browsers but there are JavaScript differences too?
So why this works in IE8:
window.print(); // works
but when I pass window.print to a function and call it, it don't work in IE8 (works in IE9):
function callIt(f){
f.call();
};
callIt(window.print);
Is it a known issue?
EDIT
OK it does not work means it will simply ignore it, no javascript error or anything.
Sorry it gives this error:
Object doesn't support this property or method
EDIT 2
I need to use call or apply since I need to pass the context. I am trying to create a class which I can pass functions and it can call it with the possibility of passing context or arguments. Do not tell me to use f() that is not an answer since it does not fix my problem. The question is on call and apply.
It seems window.* functions are separate types than user-created functions in IE < 9. Thus, they don't get any of the Function.prototype.*. You'll see that
typeof alert === 'object'
function a(){}
typeof a === 'function'
This would happen for any of the window.* functions. Only for IE < 9. WTG Miscrosoft.
However you can try
Function.prototype.call.call(window.print)
See if that works for you.
function callIt(f) {
if (f) f();
}
callIt(window.print);
Done, no?
Update
per the poster's request that I answer the question, not recommend a solution that works, here she goes:
If you view typeof(window.print) in IE, you'll see that it reports itself as type object. Type object has no apply or call method. In my opinion, your design is wrong for the task. HOWEVER, if what you want is a rabbit hole to follow, here's the top:
var p = window.print;
window.print = function() { p(); }
function callIt(f){
f.call();
}
callIt(window.print);
I have no idea what will happen in any other browser or how many procedural exceptions you'll have to make to account for it everywhere you'll need to.
You almost certainly should not be using .call() here. f() will call the method, while f.call() will call it with an unset this. Under es3 (but not es5 strict,) an undefined value for this will be coerced to window. I suspect that IE9 properly handles this, while IE8 does not, but that's just a guess based on behavior.
If print cares about the value of this, you should call it as window.print() in order for this to be set correctly. In that case, you may have to wrap it in an anonymous function so that print doesn't get "sliced off" of window. callIt(function() { window.print();});
Is there a way to make the following work?
function TimerEvent()
{
TIMER_OBJ = setTimeout('Ajaxsessioncheck();', '<%=Timer%>');
}
I am calling this function in the onload event but it is not calling the Ajaxsessioncheck function when the time has elapsed in Firefox. In IE and Chrome it works fine.
thanks for all for ur time.. i changed the code as sent timer as integer now i have a different problem. In the Ajaxsessioncheck() function i wil call a JSP page from i am not getting Response in Firefox.
You've specified '<%=Timer%>' as a string (denoted by the single quotes), where it should be an integer, like so: <%=Timer%>
You should also specify the first argument as a function reference rather than a string, so your final output would be:
setTimeout(Ajaxsessioncheck, <%=Timer%>);
you shouldn't pass the second parameter as string.
TIMER_OBJ = setTimeout('Ajaxsessioncheck();', <%=Timer%>);
should work fine. but to be even more correct, you should also avoid passing the first parameter as string, because otherwise is gets evaluated - a hidden execution of eval happens, and eval is evil. therefore, this is what you want:
TIMER_OBJ = setTimeout(Ajaxsessioncheck, <%=Timer%>);
PS. declaring a variable without using keyword var causes it to leak to the global scope. I'm not sure if you're aware of this fact.
'<%=Timer%>' is a string - it should be an int in milliseconds.
Almost all questions starting with X does not work in Y comes down to differences in browser implementation. Similar to
document.getElementById does not work in firefox and the element has a name but no ID. Works in IE but not in Fx