How to add a delay inside a loop?
Asynchronous process
const wait = ms => new Promise((resolve, reject) => setTimeout(resolve, ms)); let responseStatus = 0; // 0: Server processing, 1: Succeeded, 2: Failed while (responseStatus === 0) { // If still processing, then request async end point again const responseStatus = await ApiCall(checkStatusUrl); if (responseStatus === 1) { // Done console.log('Succeeded to fetch data'); } else if (responseStatus === 2) { // Failed console.log('Failed to fetch data'); } await wait(5000); // wait 5s }
Synchronous process
- for…
var i = 1; // set your counter to 1 function myLoop() { // create a loop function setTimeout(function() { // call a 3s setTimeout when the loop is called console.log('hello'); // your code here i++; // increment the counter if (i < 10) { // if the counter < 10, call the loop function myLoop(); // .. again which will trigger another } // .. setTimeout() }, 3000) } myLoop(); // start the loop
for (let i=0; i<10; i++) { task(i); } function task(i) { setTimeout(function() { // Add tasks to do }, 2000 * i); }
- while…
let i = 0; while (i < 10) { task(i); i++; } function task(i) { setTimeout(function() { // Add tasks to do }, 2000 * i); }
How to sort an array effeciently?
Use https://github.com/jherax/array-sort-by
// Input let rivers = ['Nile', 'Amazon', 'Congo', 'Mississippi', 'Rio-Grande']; // Output [ 'Nile', 'Congo', 'Amazon', 'Rio-Grande', 'Mississippi' ]
// temporary array holds objects with position // and length of element var lengths = rivers.map(function (e, i) { return {index: i, value: e.length }; });
// sorting the lengths array containing the lengths of // river names lengths.sort(function (a, b) { return +(a.value > b.value) || +(a.value === b.value) - 1; });
// copy element back to the array var sortedRivers = lengths.map(function (e) { return rivers[e.index]; });
How to count number of group from an array?
// How many group having 20 elements? const GROUP_LENGTH = 20 const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26] const arrLength = arr.length; const remainder = arrLength % GROUP_LENGTH; // Get remain const lessTotal = Math.floor(arrLength / GROUP_LENGTH); // Get division without remain const count = remainder > 0 ? lessTotal + 1 : lessTotal; // Count group number for (let i = 0; i < count; i += 1) { // Get array of 20 items const start = i * GROUP_LENGTH; let twentiesItems = []; if (i !== count - 1) { twentiesItems = arr.slice(start, GROUP_LENGTH); // Get 20 items } else { twentiesItems = arr.slice(start); // Get the rest of items } // Do something with array of 20 items twentiesItems ... }
Leave a Reply