What is inside Callback queue (debugger)? - javascript

I would like to know how is it possible to know the content of the callback queue.
For example, if you consider the following Javascript code :
<script>
console.clear();
setTimeout( function () {console.log("Hello ")},5000);
console.log("What is inside Callback Queue ? ");
</script>
Is there a mean to print the content of the callback queue to the console ?
If not possible in such that way, is it possible with a debugger by adding a break point to the line console.log("What is inside ...?"); (I tried with Firefox debugger but I did not manage to do it)
Or another solution ?
Thanks for answer.

The performance tab of the browser's developer tools contains all the informations needed. Do the following:
Filter markers : function call (only to avoid a lot of
informations)
Start Recording
Reload (CTRL + R)
Stop Recording (With my example, when Hello is printed to the console)
In the waterfall, Click on the mark that appears after 5000ms (with my example) and useful informations are displayed in the right pane.

While I'm not sure what your final goal is, you can wrap the function you're calling with the following wrapper function, which prints to the log whenever a function is being enqueued:
function wrapper(func) {
console.log(`'${func.name}' was enqueued`);
return func;
}
function foo() {
console.log('Hello')
}
setTimeout(wrapper(foo), 5000);
You can use a similar mechanism to maintain an array that'll contain all the functions that are currently waiting.

Related

Javascript skips piece of code but works fine when done with debugger

I have a really simple line of code. I have a tabstrip provided by Kendo library
i = 0;
x = 10;
while (i < x) {
var tabStrip = $("#myId").data("kendoTabStrip");
tabStrip.select(i);
i++;
}
When I go step by step using debugger everything is ok - tabStrip.select(i) method is being invoked and works perfectly. But when I run it without debugger it just behaves like there was no this line. I do not understand why, and I don't know how to solve this.
(i and x variables are just sample variables, maybe the information that the method is invoked inside the while loop is important)
var tabGroupObject = $("<div>").attr("id", "myId")
tabGroupObject = $(tabGroupObject).kendoTabStrip({
animation: {
open: {
effects: "fadeIn"
}
}
});
var tabStrip = tabGroupObject.data("kendoTabStrip");
Seems to be a synchronization issue, very common in JavaScript when dealing with Ajax calls or DOM modifications. That's why it works when you execute the code step by step giving enough time for the actions to happen.
My recommendation would be to read a little about Async JavaScript and try to implement a callback function that triggers once the animation finish its task.
Assumption:- I'm assuming you are looking for an ajax trigger event which gets fired in the browser in response to the select of the tabScript.
Solution:- If that's the case please know that browsers combines all the ajax events on an element within a set amount of time into one event to reduce the number of unwanted post calls, what you can do is try adding a delay if you want these events to be called else it would simply trigger the even which gets called on the tabSctrip.select(9) as mentioned by dfsq.

Different Result when function is called inside a function

I have the following JS Code which check a webpage to see if new Keys are posted on it at regular interval. Now the problem is that:
When start() is directly called from Dev Console (F12), the results are Correct and when my Function $(document).ready calls it the results are Wrong, and yes i have 100 times confirmed that no content on page is changing.
I was just curious to see if the vars are getting out of sync, so i called start() 2 times in $(document).ready, and still the wrong results but when i called satrt() from F12 (after calling it 20 times from $(document).ready, i got Correct Result.
I have confirmed that all events are waiting for each other to finsih (maybe called synchronous) and its not true that any single statement is running in a different thread.
Then how its possible that if F12 calls it, then its Correct and if $(document).ready calls it then its wrong.
A intresting point to be noted:
When i didn't had $(document).ready in my code, i called wow() from start() which also gave me wrong result, but F12 gives Correct.
Now that i have $(document).ready , if i call start() from it which inturn calls wow() gives me wrong result, but now if i call start() from my console, it gives me right result!
What i acually want to do in simpler form:
wait for page to finish loading
Call wow()
wait for wow() to finish
Reload Page
Same process continues in infinite loop.
Humble Thanks for any help, this has been wating my time for almost 5-6 hours!
JS Code : http://pastebin.com/9UJYdepU
EDIT:
Correct output:
a.js:136 Started
a.js:33 Called Wow
a.js:83 ---------------------KEY 7.0----------------
a.js:83 ---------------------KEY 7.1----------------
a.js:83 ---------------------KEY 7.2----------------
a.js:102 LAST used keys : Saab,Volvo,BMW,4E69G-8GNG4-JCZ4Z,H63HQ-VHWPX-ZCJ8J,FKZGK-MXL5C-P2YTE,4E69G-xxxxxx-JCZ4Z,4E69G-AAAxx-JCZ4Z,4E69G-AAAxx-JasasCZ4Z,4E69G-AAAxx-JasaaaasCZ4Z
a.js:140 WOWO DONW
Wrong Output:
Started
a.js:33 Called Wow
a.js:102 LAST used keys : Saab,Volvo,BMW,4E69G-8GNG4-JCZ4Z,H63HQ-VHWPX-ZCJ8J,FKZGK-MXL5C-P2YTE,4E69G-xxxxxx-JCZ4Z,4E69G-AAAxx-JCZ4Z,4E69G-AAAxx-JasasCZ4Z,4E69G-AAAxx-JasaaaasCZ4Z
a.js:140 WOWO DONW
document.getElementsByTagName("p"); Gives: http://pastebin.com/JXQ9483N
localStorage.getItem("usedp") Gives Saab,Volvo,BMW,4E69G-8GNG4-JCZ4Z,H63HQ-VHWPX-ZCJ8J,FKZGK-MXL5C-P2YTE,4E69G-xxxxxx-JCZ4Z,4E69G-AAAxx-JCZ4Z,4E69G-AAAxx-JasasCZ4Z,4E69G-AAAxx-JasaaaasCZ4Z
Finally i solved it! This was all becuase of evil Jquery (Sorry, if i hurt you).
$(document).ready was triggering when the page started loading not when it has finsihed loading, my alternate solution is:
var myVar = setInterval(function(){ chk() }, 500);
function chk(){
if(document.readyState=="complete"){
clearInterval(myVar);
startt();
}
}

These functions appear to be being executed out of order

The strangest thing just happened to me. I have some javascript that appears to be being executed in the wrong order. This is freaking me out! Observe:
the code
handleKeyDown: function (e) {
console.log("handleKeyDown");
var key = e.which;
var text = this.ui.$input.val();
if (_.isFunction(this[key])) {
// call the appropriate handler method
this[key](text, e);
console.log("before announceEdits");
this.announceEdits();
}
if (key === ENTER || key === ESC) {
console.log("fired field:key:down");
this.trigger("field:key:down", { editable: this, restore: (key === ESC) });
}
},
announceEdits: function () {
console.log("announceEdits");
var edits = this.getEdits();
console.log("edits: %o", edits.data);
console.log("fired field:edits");
this.trigger("field:edits", edits);
},
/* gather all the existing taggies */
getEdits: function () {
var data = this.$taggies().map(function (index, taggy) {
return $(taggy).data("value");
}).toArray();
var edits = {
attribute: "tags",
data: data
};
return edits;
},
When I run this code, the functions appear to be being executed out of order. This is the output in firefox's console of the above code:
the output
Notice that we get before announceEdits long before we get announceEdits, which is the first line in the annouceEdits function... my understanding of the world leads me to believe this is wrong.
what I've done
Now, I have considered the following:
The console statements could be being buffered or some such, causing them to appear out of order.
This could have something to do with the way MarionetteJS handles events.
Believing that this might be evented weirdness, I tried removing the calls to trigger (just by commenting out the lines that trigger the events). After removing the triggers, the log statements still appear out of order. So it doesn't seem to be cause by MarionetteJS's implementation of events (which is to say, BackboneJS's implementation of events ^o^//).
I'm also lead to believe that this isn't a log statement buffer issue, because the events are themselves handled out of order (i.e. the data I expect to have after the handling of the first event is not in order by the time the second event is handled). This causes the code to "not work" in the way I would like (however, see below).
In my explorations, I've tried to narrow things down a bit. I modified the code thusly, in order to simplify the code:
if (_.isFunction(this[key])) {
// call the appropriate handler method
this[key](text, e);
console.log("before announceEdits");
console.log("announceEdits");
var edits = this.getEdits();
console.log("edits: %o", edits.data);
console.log("fired field:edits");
this.trigger("field:edits", edits);
}
This way I am not descending into a subroutine. Running this code, the console statements appear in the right order. What's more interesting is that, in this case, the events are also fired and handled in the order I expect! This code works, but the one with the subroutine doesn't.
I tried to create a fiddle of this code, but jsfiddle doesn't appear to like Backbone (I tried including the library as an external library, but that didn't seem to work). I did create this fiddle, just to reassure myself that somewhere in the world there is still a rock of normality.
update: I changed the fiddle so that the main function is itself a handler. Everything still works fine in the fiddle.
how I thought the world worked
Functions create stack-frames that execute to completion. If a function calls another function, a new stack-frame is pushed to the stack. If a function triggers an event, it creates a message, which is pushed onto a message queue. Whenever (and I'm unclear on this) the stack is empty, the next message in the queue is popped off, and all handlers for this message are then invoked.
In this model, without question, the events should happen in the order that I expect (the order from the second listing). We should first descend into announceEdits, push the field:edits message to the queue, and then pop back out and push the field:key:down message. Then the handlers for field:edits should run, and finally those for field:key:down.
the question
Is there anything that could be causing these functions to be being executed out of order? Or more likely: is there anything that could be causing these functions to appear to be being executed out of order?
If this is a problem with my understanding: where did I go wrong?
If this ends up being something that was caused by a typo, please bear in mind that we are all programmers, and that we have all torn out hair and bellowed at shadows at times.
lesson
Sleep on it. In the heat of the moment, every bug is a mysterious force from another world. Step back from the problem, start from the beginning. Everything will become clear.
I came in this morning, put a debugger at the beginning of handleKeyDown and immediately saw what was wrong. It isn't in the code I gave above, naturally, and it isn't a problem with how javascript works (clearly!). I had wrapped announceEdits in a debounce earlier, to relieve a head-ache I had been having.
Good news is, my understanding of how event handling works does not appear to be in question.

Telling javascript to stop executing code and do background stuff in the middle of a function

Sorry about the title but could not come up with anything really informative and concise.
My situation is that I am launching a setTimeout and I want it to be able to run in the middle of a JS function (it is used to get around the issue with injecting GM functions into the web page).
unsafeWindow.testG = function(key, dValue){
var rValue;
setTimeout(function(){rValue = GM_getValue(key, dValue);}, 0);
alert(rValue);
alert(rValue);
return(rValue);
}
In the three tests rValue is still undefined (which makes sense because JS is single threaded for the most part).
So I have 2 solutions I have thought of.
Favourite:
Is there anyway to tell JS to sleep in the middle of a function and work on background stuff (like Timeouts)?
Other:
Does anyone know when this timeout will be called? Maybe after this function execution but before whatever called it starts up again?
In that case making rValue global would solve the issue (but make slightly messier coding).
Or will it wait until all JS is done executing?
In that case I would possibly need another setTimeout to process the result.
There is no way what you're asking for can be accompished. Until HTML5 is a wide spread standard, you can't do what you're asking without thinking asynchronously.
For example :
unsafeWindow.testG = function(key, dValue, callback){
var rValue;
setTimeout(function(){
rValue = GM_getValue(key, dValue);
callback(rValue);
}, 0);
}
and call this with a callback :
unsafewindow.testG(key, dValue, function(rValue) {
alert(rValue);
});
alert("foo");
For the last sippet, "foo" will be echoed before rValue, because testG will execute the timeout function only when the Javascript thread is available, or only when there's no other script running.
To answer your first question, there is no 'sleep' function in JS. In fact, there is a site devoted to trying to create one: http://www.devcheater.com/ The conclusion: you cannot.
If what you'd like to do is make the rest of your code run later, you can put that code in a function and setTimeout().
Of course, the usual way to handle the sort of scenario you have set up is with callbacks. Since you're basically waiting for the thing in setTimeout to happen, you can have it call the rest of your code whenever it's done. For example:
var fartResult
function waitAMinuteThenFart (callback) {
function fart () {
fartResult = 'fart'
callback(fartResult)
}
setTimeout(fart, 1000*60)
}
waitAMinuteThenFart(function (result) { alert(result) })

How would I design a client-side Queue system?

OVERVIEW
I'm working on a project and I've come across a bit of a problem in that things aren't happening in the order I want them to happen. So I have been thinking about designing some kind of Queue that I can use to organize function calls and other miscellaneous JavaScript/jQuery instructions used during start-up, i.e., while the page is loading. What I'm looking for doesn't necessarily need to be a Queue data structure but some system that will ensure that things execute in the order I specify and only when the previous task has been completed can the new task begin.
I've briefly looked at the jQuery Queue and the AjaxQueue but I really have no idea how they work yet so I'm not sure if that is the approach I want to take... but I'll keep reading more about these tools.
SPECIFICS
Currently, I have set things up so that some work happens inside $(document).ready(function() {...}); and other work happens inside $(window).load(function() {...});. For example,
<head>
<script type="text/javascript">
// I want this to happen 1st
$().LoadJavaScript();
// ... do some basic configuration for the stuff that needs to happen later...
// I want this to happen 2nd
$(document).ready(function() {
// ... do some work that depends on the previous work do have been completed
var script = document.createElement("script");
// ... do some more work...
});
// I want this to happen 3rd
$(window).load(function() {
// ... do some work that depends on the previous work do have been completed
$().InitializeSymbols();
$().InitializeBlock();
// ... other work ... etc...
});
</script>
</head>
... and this is really tedious and ugly, not to mention bad design. So instead of dealing with that mess, I want to design a pretty versatile system so that I can, for example, enqueue $().LoadJavaScript();, then var script = document.createElement("script");, then $().InitializeSymbols();, then $().InitializeBlock();, etc... and then the Queue would execute the function calls and instructions such that after one instruction is finished executing, the other can start, until the Queue is empty instead of me calling dequeue repeatedly.
The reasoning behind this is that some work needs to happen, like configuration and initialization, before other work can begin because of the dependency on the configuration and initialization steps to have completed. If this doesn't sound like a good solution, please let me know :)
SOME BASIC WORK
I've written some code for a basic Queue, which can be found here, but I'm looking to expand its functionality so that I can store various types of "Objects", such as individual JavaScript/jQuery instructions and function calls, essentially pieces of code that I want to execute.
UPDATE
With the current Queue that I've implemented, it looks like I can store functions and execute them later, for example:
// a JS file...
$.fn.LoadJavaScript = function() {
$.getScript("js/Symbols/Symbol.js");
$.getScript("js/Structures/Structure.js");
};
// another JS file...
function init() { // symbols and structures };
// index.html
var theQueue = new Queue();
theQueue.enqueue($().LoadJavaScript);
theQueue.enqueue(init);
var LJS = theQueue.dequeue();
var INIT = theQueue.dequeue();
LJS();
INIT();
I also think I've figured out how to store individual instructions, such as $('#equation').html(""); or perhaps even if-else statements or loops, by wrapping them as such:
theQueue.enqueue(function() { $('#equation').html(""); // other instructions, etc... });
But this approach would require me to wait until the Queue is done with its work before I can continue doing my work. This seems like an incorrect design. Is there a more clever approach to this? Also, how can I know that a certain function has completed executing so that the Queue can know to move on? Is there some kind of return value that I can wait for or a callback function that I can specify to each task in the Queue?
WRAP-UP
Since I'm doing everything client-side and I can't have the Queue do its own thing independently (according to an answer below), is there a more clever solution than me just waiting for the Queue to finish its work?
Since this is more of a design question than a specific code question, I'm looking for suggestions on an approach to solving my problem, advice on how I should design this system, but I definitely welcome, and would love to see, code to back up the suggestions :) I also welcome any criticism regarding the Queue.js file I've linked to above and/or my description of my problem and the approach I'm planning to take to resolve it.
Thanks, Hristo
I would suggest using http://headjs.com/ It allows you to load js files in parallel, but execute them sequentially, essentially the same thing you want to do. It's pretty small, and you could always use it for inspiration.
I would also mention that handlers that rely on execution order are not good design. I am always able to place all my bootstrap code in the ready event handler. There are cases where you'd need to use the load handler if you need access to images, but it hasn't been very often for me.
Here is something that might work, is this what you're after?
var q = (function(){
var queue = [];
var enqueue = function(fnc){
if(typeof fnc === "function"){
queue.push(fnc);
}
};
var executeAll = function(){
var someVariable = "Inside the Queue";
while(queue.length>0){
queue.shift()();
}
};
return {
enqueue:enqueue,
executeAll:executeAll
};
}());
var someVariable = "Outside!"
q.enqueue(function(){alert("hi");});
q.enqueue(function(){alert(someVariable);});
q.enqueue(function(){alert("bye");});
alert("test");
q.executeAll();
the alert("test"); runs before anything you've put in the queue.
how do I store pieces of code in the Queue and have it execute later
Your current implementation already works for that. There are no declared types in JavaScript, so your queue can hold anything, including function objects:
queue.enqueue(myfunc);
var f = queue.dequeue();
f();
how can I have the Queue do its own thing independently
JavaScript is essentially single-threaded, meaning only one thing can execute at any instant of time. So the queue can't really operate "independently" of the rest of your code, if that is what you mean.
You basically have two choices:
Run all the queued functions, one after the other, in a single go -- this doesn't even require a queue since it is the same as simply putting the function calls directly in your code.
Use timed events: run one function at a time and once it completes, set a timeout to execute the next queued function after a certain interval. An example of this follows.
function run() {
var func = this.dequeue();
func();
var self = this;
setTimeout(function() { self.run(); }, 1000);
}
If func is an asynchronous request, you'll have to move setTimeout into the callback function.
**The main functions**
**From there we can define the main elements required:**
var q=[];//our queue container
var paused=false; // a boolean flag
function queue() {}
function dequeue() {}
function next() {}
function flush() {}
function clear() {}
**you may also want to 'pause' the queue. We will therefore use a boolean flag too.
Now let's see the implementation, this is going to be very straightforward:**
var q = [];
var paused = false;
function queue() {
for(var i=0;i< arguments.length;i++)
q.push(arguments[i]);
}
function dequeue() {
if(!empty()) q.pop();
}
function next() {
if(empty()) return; //check that we have something in the queue
paused=false; //if we call the next function, set to false the paused
q.shift()(); // the same as var func = q.shift(); func();
}
function flush () {
paused=false;
while(!empty()) next(); //call all stored elements
}
function empty() { //helper function
if(q.length==0) return true;
return false;
}
function clear() {
q=[];
}
**And here we have our basic queue system!
let's see how we can use it:**
queue(function() { alert(1)},function(){ alert(2)},function(){alert(3)});
next(); // alert 1
dequeue(); // the last function, alerting 3 is removed
flush(); // call everything, here alert 2
clear(); // the queue is already empty in that case but anyway...

Categories