I spent hours reading posts all over the web about controlling execution order in Javascript/jQuery, but I still don't understand.
I'm trying to write code that shows the execution progress of behind-the-scenes javascript on a webpage. I have a jsfiddle (http://jsfiddle.net/wlandau/9sbu9myb/) that accomplishes this using timeouts. The javascript is
var showProgress = function(x){
$(".progress").hide();
$(x).show();
}
var step1 = function(){
showProgress(".running");
};
var step2 = function(){
for(var i = 0; i < 1000000000; ++i)
i = i + 1;
};
var step3 = function(){
showProgress(".done");
};
$(".begin").click(function(){
step1();
setTimeout(step2, 0);
setTimeout(step3, 0);
});
$(".clear").click(function(){
$(".progress").hide();
});
I will eventually need to use ajax and php, and I've read that the recommended tools are when/then, Deferred objects, and promises. So I tried (http://jsfiddle.net/wlandau/an8moww6/), but the execution order is wrong. (The html page doesn't say "Running..." when the for loop is running.) That fiddle's javascript is
var showProgress = function(x){
$(".progress").hide();
$(x).show();
}
var step1 = function(){
var def = $.Deferred();
showProgress(".running");
return def.promise();
};
var step2 = function(){
var def = $.Deferred();
for(var i = 0; i < 1000000000; ++i)
i = i + 1;
return def.promise();
};
var step3 = function(){
var def = $.Deferred();
showProgress(".done");
return def.promise();
};
var success = function(){
console.log("success")
};
var failure = function(){
console.log("failure")
};
$(".begin").click(function(){
$.when(step1(), step2(), step3()).then(success, failure);
});
$(".clear").click(function(){
$(".progress").hide();
});
QUESTION 1 (first fiddle): When I change "step1()" to "setTimeout(step1, 0)" in the "$(".begin").click(function(){..}" block, the execution order breaks down. Why is this?
QUESTION 2 (second fiddle): Why is the execution order wrong when I try to use when/then/Deferred/promise?
QUESTION 3 (second fiddle): Why isn't the "success" function executing? I told it to print to the console, but the Chrome's Javascript console shows nothing.