Вы можете сделать это с помощью некоторого трюка - с помощью прерывания функции setTimeout
.Например, без дополнительного потока невозможно параллельное выполнение 2 функций, но с помощью трюка прерывания функции setTimeout
мы можем сделать это следующим образом:
Пример параллельного выполнения функций
var count_0 = 0,
count_1 = 0;
function func_0()
{
if(count_0 < 3)
setTimeout(func_0, 0);//the same: setTimeout(func_0);
console.log('count_0 = '+count_0);
count_0++
}
function func_1()
{
if(count_1 < 3)
setTimeout(func_1, 0);
console.log('count_1 = '+count_1)
count_1++
}
func_0();
func_1();
Вы получите этот вывод:
count_0 = 0
count_1 = 0
count_0 = 1
count_1 = 1
count_0 = 2
count_1 = 2
count_0 = 3
count_1 = 3
Почему это возможно?Потому что для выполнения функции setTimeout
требуется некоторое время.И даже этого времени достаточно для выполнения некоторой части из вашего следующего кода.
Решение для вас
Для этого случая вам нужно написать собственную функцию сортировки массива(или вы также можете использовать следующую функцию от меня), потому что мы не можем прервать встроенную функцию sort
.И в этой вашей собственной функции вы должны использовать эту setTimeout
функцию, которая прерывает трюк.И вы можете получить ваше message
уведомление о событии.
В следующем примере у меня есть прерывание на половину длины моего массива, и вы можете изменить его, если хотите.
Пример с прерыванием пользовательской сортировки
var numbers = [4, 2, 1, 3, 5];
// this is my bubble sort function with interruption
/**
* Sorting an array. You will get the same, but sorted array.
* @param {array[]} arr – array to sort
* @param {number} dir – if dir = -1 you will get an array like [5,4,3,2,1]
* and if dir = 1 in opposite direction like [1,2,3,4,5]
* @param {number} passCount – it is used only for setTimeout interrupting trick.
*/
function sortNumbersWithInterruption(arr, dir, passCount)
{
var passes = passCount || arr.length,
halfOfArrayLength = (arr.length / 2) | 0; // for ex. 2.5 | 0 = 2
// Why we need while loop: some values are on
// the end of array and we have to change their
// positions until they move to the first place of array.
while(passes--)
{
if(!passCount && passes == halfOfArrayLength)
{
// if you want you can also not write the following line for full break of sorting
setTimeout(function(){sortNumbersWithInterruption(arr, dir, passes)}, 0);
/*
You can do here all what you want. Place 1
*/
break
}
for(var i = 0; i < arr.length - 1; i++)
{
var a = arr[i],
b = arr[i+1];
if((a - b) * dir > 0)
{
arr[i] = b;
arr[i+1] = a;
}
}
console.log('array is: ' + arr.join());
}
if(passCount)
console.log('END sring is: ' + arr.join());
}
sortNumbersWithInterruption(numbers, -1); //without passCount parameter
/*
You can do here all what you want. Place 2
*/
console.log('The execution is here now!');
Вы получите следующие выходные данные:
массив: 4,2,3,5,1
массив: 4,3,5, 2,1
Выполнение здесь! * Массив
: 4,5,3,2,1
Массив: 5,4,3,2,1
END sring:5,4,3,2,1