Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
Only execute a function once in a given amount of time

I have an api request that is called multiple times in a given amount of time. More specifically this request is for refreshing the user token, so it's called on every request, which adds up pretty quickly. I would like to create a function that tells the function not to run for a given amount of seconds. I have tried using lodash debounce but I can't get it to work.

let debounceRefresh;

debounceRefresh = debounce(() => {
  api.request(){
  });
}, 1000);

debounceRefresh();

Am I executing this wrong? Is it possible to do?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Yes, you definitely need throttle for the job.

// in this example we invoke a fn for a period of 10 sec, invoking it 2 times a second, but we can perceive that the original function is only invoked at most once per 2 seconds according to the parameter below:

var TOTAL_TIME_TO_RUN = 10000; // 10 sec
var THROTTLE_INTERVAL = 2000; // <= adjust this number to see throttling in action
var INVOCATION_INTERVAL = 500; // 0.5 sec

// regular fn
var punchClock = function punchClock() {
  console.log(new Date().toISOString() + ' - call api');
};

// wrap it and supply interval representing minimum delay between invocations
var throttledPunchClock = _.throttle(punchClock, THROTTLE_INTERVAL);

// set up looping
var intervalId = setInterval(function() {
  console.log("attempting call api");
  throttledPunchClock()
}, INVOCATION_INTERVAL);

// run the demo
setTimeout(() => clearInterval(intervalId), 10000)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<pre>
  var TOTAL_TIME_TO_RUN = 10000; // 10 sec
  var THROTTLE_INTERVAL = 2000; // < = adjust this number to see throttling in action
  var INVOCATION_INTERVAL = 500; // 0.5 sec
</pre>

Snippet from github

about 4 years ago · Juan Pablo Isaza Report

0

Have you tried with a timeout?

const myTimeout = setTimeout(debounceRefresh, 1000);

If the function is called again, you can clear the timeout and reset it

clearTimeout(myTimeout);

Why don't you use a different listener? Perhaps when data is received?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!