简体   繁体   中英

Issue with Lodash Throttle or Debounce within the loop

I'm calling a fetch request which I'm trying to limit by using Lodash Throttle or Debounce. I'm looping through some array and calling function instantly which effects a server to respond with 502. I'm trying to slow down the requests with Throttle. The code below should explain my structure. This example does not work and I don't know why?


    function doSomething(i) {
      console.log('Doing something: ' + i)
    }


    for (var i = 0; i < 50; i++) {

       _.throttle( function() { doSomething(i) }, 15000);

    }

The function doSomething() should be called every 15 seconds and additional requests to this function should be stacked.

_.throttle() is not meant to be used this way. Right way to go is to store the result first.

var throttledDoStomething = _.throttle(doSomething, 15000)

for (var i=0; i < 50; i++) {
  throttledDoSomething(i)
}

In reply to the comment:

In that case, throttle maybe is not the right choice. You might want to use asynchronous function by using Promise.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

function asyncDoSomething(i) {
  return new Promise((resolve, reject) => {
    console.log('Doing something: ' + i);
    setTimeout(()=>{
      resolve(i);
    }, 15000)
  })
}

async function doSomethingLoop() {
  for (var i = 0; i < 50; i++) {
    await asyncDoSomething(i);
  }
}

doSomethingLoop();

Document suggests that you should first make throttled function.
Putting argument needs Anonymous function(in my case, I used Array function) to be used.

function doSomething(i) {
  console.log("Doing something: " + i);
}

const throttledSomething = _.throttle(() => { doSomething(i)}, 5000);

for (var i = 0; i < 50; i++) {
  throttledSomething(i);
}

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