New Year Chaos JavaScript, needs to be sped up Similar to this question but this is for Python

Original problem with description on hacker rank

I am currently trying to iterate through a large number of arrays and count how many times numbers have been swapped.

A sorted array looks like this: [1,2,3,4,5] and a number can be swapped only towards the front (counting down to 0) twice.

If a number is more than 2 out of order the array is deemed 'Too chaotic' and the process should stop.

Instead of bubble sorting I am simply going through and counting the actual swaps. As a sorted array is not actually required, my code works except for a couple of the tests where it times out due to large arrays.

Any ideas on how to speed this process up?

function minimumBribes(q) {
console.log(sort(q));

    function sort(items) {
     let bribes = 0;

     for (let i = 0; i &lt; items.length; i++) {
         if (items[i] - (i + 1) &gt; 2) return "Too chaotic";
         for (let j = 0; j &lt; i; j++) {
             if (items[j] &gt; items[i]) bribes++;
         }
     } 
     return bribes;
   }
}
Reduce the inner loops iteration count.
The problem is the inner loop is looping over too many items. The result is that you spend too much time processing data you know is irrelevant.
As the function should exit if it detects a position has made over 2 bribes, you need only have the inner loop check positions down 2 from the item you are checking, and not from the start of the line.
Quicker solution
It only requires a slight modification of your code, but as you have complicated the situation by calling an inner function sort the example has just removed the inner function.
The line for (j = pos-2; j &lt; i; j++) { is where the improvement is with pos being item[i] in your function.
function minBribe(queue) {
    var bribes = 0, i, j;
    for (i = 0; i &lt; queue.length; i++) {
        const pos = queue[i], at = i + 1;
        if (pos - at &gt; 2) { return &quot;Too chaotic&quot; } 
        for (j = Math.max(0, pos - 2); j &lt; i; j++) {
            if (queue[j] &gt; pos) { bribes++ }
        }
    } 
    return bribes;
}

This brings the solution down from \$O(n^2)\$ to near \$O(n)\$ however the number of bribes is a factor so its closer to \$O(n + (m^{0.5}/2))\$ where \$m\$ is the number of bribes. (this is only an approximation)