简体   繁体   中英

setTimeout inside for loop with random values

Problem is that setTimeout function within for loop is not getting the correct values despite the fact they were passed correctly. Second problem is that the sleep variable is not working, it simply ignores it. Other variables like i are acting strange, they are not going though the loop, they are going in a random order.

Inside function set_delay

console.log(i); 
// 3,5,0,2,4,1 should be 0,1,2,3,4,5
console.log(sleep); 
// 6000,6000,7000,9000,9000,10000, those ones are displayied in ASC order but shuold be randomly
console.log(share_screen_rate[i]); 
//4,1,6,10,6,2,8 - this is not ok it's random
console.log(top); 
// 749.5,2998,299.8,499.667,149,374.75 =>  this should be in order from smallest (149) to biggest (2998)

setTimeout(function() {

}, sleep);

if I change sleep to a numeric value like 2000 it is respected only for first iteration after nothing, it just goes at 0ms.

FULL CODE

https://jsfiddle.net/ojpv2nxu/

EXPECTED OUTPUT

This should be a simple script to scroll down the page and make pause based on the sleep variable and also read the page chunk by chunk based on the share_screen_rate variable

I think it is a logic issue.... You are expecting the setTimeout to happen x seconds after the last one. But they are firing x seconds after you set it. So it is working as expected.

If you want them to fire x seconds after the last, than you need to change the logic to keep track of the seconds and adjust the timers.

so top of the file add

var timeTrack = 0

and than you need to add to that value

timeTrack += sleep
setTimeout(function() {

}, timeTrack);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM