Skip to content

Instantly share code, notes, and snippets.

@dingjing
dingjing / loop-promise.js
Last active August 29, 2015 13:56
Post-promise loop example
function doTask(i){
// Create a new process.
var defer = $.Deferred();
// Start main task in the process
setTimeout(function(){
log("Step " + (i+1) + " finished.");
// Terminate the processs upon successful finish.
defer.resolve(i);
@dingjing
dingjing / branch-async.js
Created February 28, 2014 04:58
Asynchronous version of branch example.
function doTask1(add, multiply){
setTimeout(function(){
var rslt = Math.floor(Math.random() * 10);
log("Task 1 returned " + rslt);
if(rslt >= 5)
add(rslt);
else
multiply(rslt);
}, 500);
}
@dingjing
dingjing / branch-sync.js
Created February 28, 2014 04:52
Synchronous version of branch example.
function doTask1(){
var rslt = Math.floor(Math.random() * 10);
log("Task 1 returned " + rslt);
return rslt;
}
function addTask(i){
var rslt = Math.floor(Math.random() * 10);
log("addTask finished with " + rslt);
return i + rslt;
@dingjing
dingjing / loop-recursive-callback.js
Created February 28, 2014 04:44
Restore loop sequence using recursive callbacks.
function doTask(i){
setTimeout(function(){
if(i < 5){
log("Step " + ++i + " finished.");
doTask(i++);
}else
log("All steps done.");
}, Math.random()*1000);
}
@dingjing
dingjing / loop-nested-callback.js
Created February 28, 2014 04:37
Restore loop sequence using nested callbacks.
function doTask(i, next){
setTimeout(function(){
log("Step " + ++i + " finished.");
next();
}, Math.random()*1000);
}
$(function(){
doTask(0, function(){
doTask(1, function(){
@dingjing
dingjing / doTask-async.js
Created February 28, 2014 04:28
Async version of doTask()
function doTask(i){
setTimeout(function(){
log("Step " + ++i + " finished.");
}, Math.random()*1000);
}
@dingjing
dingjing / loop-sync.html
Created February 28, 2014 04:12
Synchronous loop example
<div id="log"></id>
<script type="text/javascript">
var log = function(content){
$('<p/>').html(content).appendTo('#log');
}
function doTask(i){
log("Step " + ++i + " finished.");
}
@dingjing
dingjing / post-ajax.js
Created February 28, 2014 04:01
Post-promise ajax call
$.ajax("http://somewhere.net")
.success(function(){ alert("success"); })
.error(function(){ alert("error"); });
@dingjing
dingjing / pre-ajax.js
Created February 28, 2014 04:00
Pre-promise ajax call
$.ajax({
url: "http://somewhere.net",
success: function(){ alert("success"); },
error: function(){ alert("error"); }
});
@dingjing
dingjing / reorder.js
Created February 19, 2014 19:09
Reorder rows
<script type="text/javascript">
function reorder(table, row) {
if(!table)
table = $("#QuizTable")[0];
var rows = table.tBodies[0].rows;
var step = 1;
for (var i = 1; i < rows.length; i++) {
$(".orderbox", rows[i]).val(step++);
}