What steps should I take to optimize the performance of this code by implementing rate-limiting for its execution speed?

As I pondered the task at hand, I realized that using a sleep function might be beneficial. However, Javascript lacks a built-in sleep function.

How can I tweak this process to avoid hitting a Parse rate-limit? My goal is to execute one (1) Parse.Cloud.run method every 5 seconds.

$('.website').each(function(i) {
    var website = $(this).text();
    Parse.Cloud.run('getMainEmail', {url: website}, {
        success: function(result) {
            cell.next().text(result);
        },
        error: function(error) {
            console.log("Couldn't find email for website: " + website);
            console.log(error);
        }
    });
});

Currently, the code scans all websites in the DOM and triggers numerous Parse requests simultaneously - resulting in an immediate rate limit restriction.

Answer №1

You can achieve this by using the setTimeout function and passing the website as a parameter.

$('.website').each(function(i) {
    var website = $(this).text();
    setTimeout(function(siteText){
    Parse.Cloud.run('getMainEmail', {url: siteText}, {
        success: function(result) {
        cell.next().text(result);
    },
    error: function(error) {
        console.log("Couldn't find email for website: " + siteText);
        console.log(error);
    }
    }, (i + 1) * 5000, website);
});

Answer №3

To effectively manage the actions, consider using a queue implementation:

var timer;
var queue = [];
function addToQueue(website) {
    queue.push(website);
    if (!timer) {
        processNextItem(); // initiate handling of first item immediately
        timer = setInterval(processNextItem, 5000);
    }
}

function processNextItem() {
    var website = queue.shift();
    if (queue.length === 0 && !timer) { 
        clearInterval(timer); // stop the timer
        timer = null;
    }

    Parse.Cloud.run('getMainEmail', {url: website}, {
        success: function(result) {
            cell.next().text(result);
        },
        error: function(error) {
            console.log("Error finding email for website: " + website);
            console.log(error);
        }
    });
}

Your original code can then be modified to:

$('.website').each(function(i) {
    addToQueue($(this).text());
});

If a slight delay before processing the first item is acceptable, you can simplify the design by having a continuous interval running:

var queue = [];
setInterval(function () {
    if (queue.length) { 
        var website = queue.shift();
        Parse.Cloud.run('getMainEmail', {url: website}, {
            success: function(result) {
                cell.next().text(result);
            },
            error: function(error) {
                console.log("Error finding email for website: " + website);
                console.log(error);
            }
        });
   }
}, 5000);

$('.website').each(function(i) {
    queue.push($(this).text());
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The project is throwing an error: Unable to locate module './lib/md5-hex' in Ember JS

I attempted the following steps: uninstalling md5-hex using npm with the command: npm uninstall md5-hex --save reinstalling md5-hex using npm with the command: npm install md5-hex --save After performing these actions, I ran ember s but unfortunately, i ...

JavaScript - Navigating through JSON object in reverse (from leaf to root) direction

FamilyTree= { "name":"Family", "photo":"images/family.jpg", "members":[ { "name":"Parent", "photo":"images/parent.jpg", "relationships":[ { "name":"Spouse", "photo":"images/spouse.jpg" }, ...

The JavaScript Discord Bot is having trouble connecting to a voice channel

I'm currently working on developing a discord bot using node.js. While I've successfully set it up to respond, I'm facing an issue with summoning it to a voice channel. Here is the snippet of code I am working with: switch (args[0]) { c ...

What is the right way to send a success response from Express JS to Backbone when logging out a user?

I'm currently learning how to work with Express JS and Backbone. On the server side using Express.js, I have this code snippet for logging out a user: app.get('/logout', function(req, res) { req.logout(); res.send('How can I ...

Populate a pair of div elements using just one AJAX request

Currently, I am attempting to use the load() function to ajaxly load two separate divs, #follow-x and #follow-y, by clicking a button. The approach I have taken is as follows within the success function of my code snippet. However, this method does not see ...

What is the reason for and <br> not functioning in a string?

I am encountering an issue when attempting to print the content of an object. Some of the properties within the object contain tags, making it challenging to create new elements in JavaScript without knowing which properties will include these tags. How ...

Do API applications require a session to function properly?

I am in the process of developing an API and I am unsure whether I should implement express-session or a similar tool to handle sessions. app.use(expressSession({ secret: 'Something' }); Moreover, I have been blocking CORS. Is this measure suf ...

Is there a way to retrieve the current logged in user when working with socket.io?

When it comes to retrieving the logged in user using passport.js in most of my routes, it's a breeze - just use req.user.username. However, I've encountered an issue with a page that relies solely on websockets. How can I determine the username o ...

Is it possible to transmit both HTML and PHP files using express.js?

Is it possible to serve HTML files for one page and PHP files for another with an express.js app? Here's a theoretical example: var express = require('express.js') var app = express() app.get('/php', function (req, res) { res.se ...

The JavaScript Top Slide Down effect is malfunctioning

Every time I press the "More" button, I expect some forms to pop out but nothing happens. Can someone please assist me with this issue? <body> <!--Hero Image--> <div class="hero-image"> <div class="hero ...

Error Alert: The combination of React and Redux-router is causing an unexpected issue. The reducer is expected to be a

Whenever I make a coding mistake and encounter a runtime error, the error reporting is not very helpful. For example, when I mistakenly typed Date() instead of new Date(), the error message I received was... Uncaught Error: Expected the reducer to be a fu ...

Angular's ng-submit directive does not use the most up-to-date scope available

I'm currently learning Angular and have been struggling with a particular issue. I have created a form to edit user details. Upon page load, I make an AJAX call to fetch the data of the selected user and populate the scope with the values. Initially, ...

detecting key presses on documents using javascript

I'm having trouble capturing document-level key press events on a webpage. I've tried using the following code: $(document).bind('keydown', 'a', keyevent_cb); It works fine in IE, but it's not consistent in Firefox. I&a ...

JavaScript for beginners: show a specified amount of search results and insert a loading indicator at the end

Currently, I have a website that retrieves data from my database using a PHP query. However, the issue I am facing is that there are over 300 entries in my database, resulting in an excessively long displayed page. My main question: How can I restrict ...

Conceal overflow in SVG after stroke is applied to top rectangle border

Is there a way to conceal the overflowing red color in this SVG? I attempted repositioning it before the rect with the stroke, but that didn't solve the issue. Check out the code and screenshot below. <br><br> <svg _ngcontent-fdl-c1 ...

Verification of javascript for an unpredictable image generator script

When running the W3C Validation tool, an error is returned stating 'img not acceptable here.' Any suggestions on how to resolve this issue? <script type="text/javascript" language="JavaScript"> NumberOfImagesToRotate = 9; FirstPart = &ap ...

Error: Comparison of two objects cannot be performed in Node.js due to AssertionError

Utilizing the functions below to retrieve a value from the application and compare it with the expected value. However, encountering issues with the output displayed. Seeking assistance in resolving this matter. getEleAttribute = async function(ele, attr) ...

When running `aws-cdk yarn synth -o /tmp/artifacts`, an error is thrown stating "ENOENT: no such file or directory, open '/tmp/artifacts/manifest.json'"

Starting a new aws-cdk project with the structure outlined below src └── cdk ├── config ├── index.ts ├── pipeline.ts └── stacks node_modules cdk.json package.json The package.json file looks like this: " ...

Send the data to be placed in the div to launch the window

I'm attempting to open a new window within the same tab and transfer some html code to be inserted into a specific div section of the newly opened window. However, I'm encountering difficulties in passing the data as illustrated below: JavaScrip ...

Node Selenium for Importing Excel Files---I will help you

My current challenge involves using node selenium in Firefox to click a link that triggers the download of an excel file. I want the downloaded file to be saved in a specific directory, but when I click the link, a dialog box pops up giving me the option ...