This script should scroll through each container on a website with a randomly generated delay.
I want to replace the "pause" of 2000
ms with a randomly generated number between min
and max
seconds for each iteration in the loop.
var min = 3,
max = 9;
var y = document.querySelectorAll('.chunk-container').length;
for (let x=0; x<y; x++) {
task(x);
}
function task(x) {
// var z = randomGen() * 1000;
setTimeout(function() {
console.log('X = ' + x + ' Y = ' + y);
document.getElementsByClassName('chunk chunk-container')[x].scrollIntoView({behavior: 'smooth'});
console.log('Scrolled to next Container');
}, /* z */ 2000 * x);
}
})
Random number generator:
function randomGen() {
var rand = Math.floor(Math.random() * (max - min + 1) + min);
console.log('Random Number generated: ' + rand + ' seconds');
return rand;
}
Like this it works fine. After each iteration, there is a 2 second pause. However when I remove the comments to add the lines var z = randomGen() * 1000;
to randomize the time between each iteration, the x
value (at which container it should scroll to) starts off fine, but then turns out random as well.
The console output:
Random Number generated: 6 seconds
Random Number generated: 5 seconds
Random Number generated: 4 seconds
Random Number generated: 8 seconds
Random Number generated: 4 seconds
Random Number generated: 8 seconds
X = 0 Y = 7
Scrolled to next Container
X = 1 Y = 7
Scrolled to next Container
X = 2 Y = 7
Scrolled to next Container
X = 4 Y = 7
Scrolled to next Container
X = 3 Y = 7
Scrolled to next Container
X = 5 Y = 7
Scrolled to next Container
X = 6 Y = 7
Scrolled to next Container
How can I fix this?
I rewrote you code.
I think the main problem was that setTimeout
is non blocking.
I used promise
together with await
to solve it
function sleep(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
function randomGen(max, min) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
async function randomWaitAndScroll(elements, timeMin, timeMax) {
for (element of elements) {
let random = randomGen(timeMin, timeMax)
await sleep(random);
element.scrollIntoView({behavior: 'smooth'});
}
}
const containerElements = document.querySelectorAll('.chunk-container');
randomWaitAndScroll(containerElements, 3000, 9000);