asynchronous - Async run for javascript by using listeners -
i have 2 functions, names function3, function4, function3 send request server side jsondata using ajax, which, however, take 3 seconds complete. function4 common function wait function3's result , action. code puts below:
function ajaxrequest(container) { $.ajax({ url: "home/getresult", type: "post", success: function (data) { container.append(data.message); } }); } var eventable = { on: function (event, cb) { $(this).on(event, cb); }, trigger: function (event) { $(this).trigger(event); } } var function3 = { run: function () { var self = this; settimeout(function () { ajaxrequest($(".container1")); self.trigger('done'); }, 500); } } var function4 = { run: function () { var self = this; settimeout(function () { $(".container1").append("function4 complete"); self.trigger('done'); },500); } } $.extend(function3, eventable); $.extend(function4, eventable); function3.on('done', function (event) { function4.run(); }); function4.on('done', function () { $(".container1").append("all done"); }); function3.run();
but problem is, when start code , show me result : first appear "function4 complete", "all done" follows, 3 seconds later, "function3 complete" appear.
that's out of expection because expection "function3 complete" comes first, "function4 complete" comes second , "all done" expected last one.
anyone can me on this? thx in advice.
edit:
have included functions above now.
also, can check js script in jsfiddle : http://jsfiddle.net/sporto/fybjc/light/
have replaced function in jsfiddle common array push action ajax request, things run out of expection.
you need call function4()
within success-function follows ajax-request function3()
makes. way function4
executed after function3
.
and might suggest more suggestive function names:)
and don't think need timeouts then
Comments
Post a Comment