Call a function when other async functions have finished, pure javascript

Assuming you have a <div id=”x”> or just output to the console

/* This demonstrates how to call a function when two other async functions, f1 and f2, have finished.
f1 and f2 use setTimeout, which is async, meaning the rest of the code will run immediatly after being called, and a callback function will be called when setTimeout has finished.
setTimeout has to be understood as calls to API server functions that can take some time to execute
*/
var req1, req2 = false // flags to know when functions are done. It can very well be a counter if there are many and you don't need to know which function has finished.
x.innerHTML= "waiting for f1 and f2 to end in order to call f3...<br>"
// f1 and f2 are called at the same time
f1();
f2();

function f1(){
x.innerHTML = x.innerHTML + "f1 called...<br>"
setTimeout(function afterThreeSeconds() {
	req1=true;
  x.innerHTML = x.innerHTML + "f1 finished. <br>"
  if (req1&&req2){f3()}
}, 3000)}

function f2(){
x.innerHTML = x.innerHTML + "f2 called...<br>"
setTimeout(function afterTwoSeconds() {
	req2=true
    x.innerHTML = x.innerHTML + "f2 finished. <br>"
  if (req1&&req2){f3()}
}, 2000)}

// f3 will be called immediately after both f1 and f2 are done
function f3(){
	x.innerHTML = x.innerHTML + "f3 called because f1 & f2 finished :)"
}

 

Evaluate an object looping back its nodes

The situation is that you want to avoid lines like this one here

if (object.key == null || typeof(object.key)=== "undefined" || object.key==="")

 

Which can be terrible when there areĀ object.grandparent.parent.child and any of them could be undefined.

Considering that eval() isn’t evil, just misunderstood, this solution verifies that all the nodes exist and the “leaf” has a value other than “”

function hasContent(obj, string) {
    st = string.split(".");
    var key, v;
    try {
        key="";
        for (v = 0; v < st.length; v++) {            
            key=(key=="")?st[v]:key+'.'+st[v];
            if (eval("obj."+[key]) === null ||  typeof (eval("obj."+[key])) === "undefined") return false;
        }
        if (eval("obj."+[key])=="") return false
    }
    catch (e) { return false; }
    return true;
}

 

The usage is fairly simple: just call the function sending your object and the string having the full path

if (hasContent(timeEntry,"UserComments.UserComment"))

 

Eval, not evil

Console.log(all jQuery events)

JavaScript – jQuery

Sometimes you just don’t know which of your events are triggered, or whether they are triggered twice because of combined handlers (ie mousedown, click, focusin) And then, setting a million console.log() in your code is just not working.

Try to just put this piece of code at the beginning:

$(document).on("click mousedown mouseup focus blur keydown change focus focusin focusout",function(e){
   console.log(e);
 });

 

It will display all the events on your console as they happen

Beautiful, uh?