Sunday, 11 September 2016

javascript - Force code to execute after another method finishes executing



Here is what I want to do:



setSource is a function which executes about 3 seconds.



 editor.setSource();

setTimeout(function () {
//do something, some commands

}, 3000);


I want the //do something, some commands part to be executed AFTER the last line of setSource() is executed. Now I'm doing it with setTimeout, but I think it's not very good solution, because sometimes setSource() will take maybe 5 seconds to execute. How to do this?


Answer



Have setSource take a callback argument:



editor.setSource = function(callback) {
// do editor things
callback();

}


Then pass the next block of code to be executed as a callback:



editor.setSource(function() {
// do some other things
});






If you have access to jQuery's deferred objects, you can make use of them here:




  1. Make a new deferred object.

  2. Start the timeout to do your long task.

  3. Return the deferred object.

  4. In the timeout, once the task is complete, call deferred.resolve.






editor = {
setSource: function() {
var deferred = $.Deferred();

console.log("Beginning editor.setSource...");

setTimeout(function() {

// This function took a while to occur
deferred.resolve();
}, 3000);

return deferred;
}
}

$.when(editor.setSource()).then(function() {
console.log("Editor is done!");

});


If you're doing AJAX or animation or another jQuery task that uses deferred objects already, you can just return its result value instead of making your own deferred object:



editor = {
setSource: function() {
return $.get({
url: "myurl.com/mypage",
data: $("#myform").serialize()

});
}
}

$.when(editor.setSource()).then(function() {
console.log("Editor is done!");
});


Make sure to look up how you can either resolve or reject deferred objects, and how to handle those.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...