a/19763265/1636522
by wared
HTML
<div style="margin-bottom:15px">
<button>Click me first</button> <span></span><br/>
<button>Then click me</button><br/>
<button>Clear</button>
</div>
<div id="log"></div>
CSS
*{font-family:Consolas}
#log div{border-bottom:1px solid #cccccc;padding-bottom:4px;margin-bottom:4px;}
JavaScript
var count = 0;
$('button:eq(2)').click(function () {
$('#log').empty();
});
$('button:eq(0)').click(function () {
output('First button clicked');
output('Wait until Ajax request completes');
ajax();
});
refreshCounter();
output('Click the first button');
function ajax() {
var tid, delay = Math.round(Math.random() * 3) + 1;
$.ajax({
url: '/echo/json/',
type: 'POST',
data: { delay: delay },
success: function () {
tid && clearTimeout(tid);
output('Ajax request completed');
output('Click the second button');
refreshCounter();
$('button:eq(1)').click(function () {
output('Second button clicked');
output('Click the first button again');
});
}
});
tid = setTimeout(function () {
tid = null;
output('Ajax request failed, please retry');
output('Click the first button');
}, (delay + 1) * 1000);
}
function refreshCounter(str) {
$('span').text('Successful clicks : ' + (count++));
}
function output(str) {
$('#log').append('<div>' + str + '</div>');
}