The Javascript engine executes functions one by one, taking them from the queue. Functions can be added either using a script or as a result of user actions (event handlers). Therefore, the idea is to divide a long-term task into small short-term subtasks and transfer them to this โqueueโ in such a way that they can be mixed with functions that correspond to user actions.
This can be done by calling the setTimeout window with a zero delay and passing your subtask as a function. So you give a chance to the UI event handler earlier
function plotSpot(spot) {
Here is the extension for the Array prototype:
Array.prototype.forEachInBatches = function(batchSize, func) { var arr = this; var i = 0; var doer; doer = function() { setTimeout(function() { for (var stopBatch = i + batchSize; i < stopBatch && i < arr.length; i++) { func(arr[i], i); } if (i < arr.length) { doer(); } }, 0); }; doer(); };
Usage example (you should have a div with a spot id somewhere in the document). To see the difference, set the batch size to the number of spots:
var spots = []; for (var i = 0; i < 10000; i++) { spots.push('{x: ' + Math.ceil(Math.random() * 180) + ', y: ' + Math.ceil(Math.random() * 180) + '}'); } spots.forEachInBatches(10, function(spot, i) { document.getElementById('spots').innerHTML += spot + (i < spots.length ? '; ' : ''); });
source share