Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rate limit how fast a javascript function allows itself to be called?

Tags:

I have a JavaScript function which actually ends up making a server-side call. I want to limit the rate at which this function can be called.

What is an easy way I can limit how fast my javascript function will get called by say 200-500 milliseconds or so? Should I use a javascript timer control?

like image 430
Hendo Avatar asked May 27 '10 19:05

Hendo


People also ask

How is rate limiting implemented in JavaScript?

Rate limiter implementation using third party library In the index. js file, add the following code: const express = require("express"); const indexRoute = require("./router"); const rateLimit = require("express-rate-limit"); const app = express(); const port = 3000; app.

What is limit in JavaScript?

Limit a JavaScript String to N CharactersThe limit method returns the original string if its length is shorter than or equal to the given limit.

How does a rate limiter work?

How does rate limiting work? Rate limiting runs within an application, rather than running on the web server itself. Typically, rate limiting is based on tracking the IP addresses that requests are coming from, and tracking how much time elapses between each request.


2 Answers

Libraries like bottleneck and node-rate-limiter pretty much cover all use cases.

like image 82
thisismydesign Avatar answered Sep 24 '22 13:09

thisismydesign


If your problem involves too much work being created, use a queue:

const work_queue = [];  function queue(message) {   work_queue.push(message)   }   function run() {   const work = work_queue.shift();   if (work !== undefined) {     scan_one(work);   } }  setInterval(run, 15); 

If you problem involves a function being called too often:

let last = +new Date();  function run() {   const now = +new Date();   if (now - last > 5000) { // 5 seconds     last = now;     run_once();   } }    
like image 38
Stephen Avatar answered Sep 25 '22 13:09

Stephen