6

I need to sort a big list of Javascript items and I'm using the sort function like this:

var sorted_list = non_sorted.sort(function(a,b){
// Sort stuff here
});

What I'd like to do is to call a function when the sort function is done.

Is it possible to add a callback function to sort or to trigger an event when when sort is over?

3
  • 5
    You can just add the function to call after you've sorted the list. Commented Oct 23, 2015 at 0:20
  • 4
    .sort() is synchronous. Commented Oct 23, 2015 at 0:33
  • 1
    As suggested, you can do arr.sort(comparefn).arrMethod() or someFn(arr.sort(comparefn)) since sort returns the sorted object. Commented Oct 23, 2015 at 0:35

3 Answers 3

16

You are overcomplicating it. The sort method isn't asynchronous, so you don't need a callback or an event. Just put your code after the code that calls sort:

var sorted_list = non_sorted.sort(function(a,b){
  // comparer
});
// The code just continues here after the sort
Sign up to request clarification or add additional context in comments.

Comments

0

The sort function is synchronous so you can simply do something right after the call but if you want another way:

Array.prototype.sortCallback = function(compareFunction, resultFunction){
    result = this.sort(compareFunction);
    resultFunction(result);
}

Usage:

non_sorted.sortCallback(function(a, b) {
  // Sort stuff here
}, function(sorted) {
   // Do something with the sorted array
});

2 Comments

@epascarello just for the hell of it :P And I figured I'd make it a prototype just to show how this can be done.
Consider replacing resultFunction(result) with resultFunction.apply(result, arguments) to allow arguments to be passed to resultFunction. But extending built–ins isn't a good idea.
-5

this is a little dirty but it works:

slow enough for the sort function (within reason) and faster than the naked eye.

function sort_with_callback() {

            run_sort_function();

            setTimeout(function() { run_callback()},  3);}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.