Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Limit JavaScript to run X amount of times

I have this JS function that its designed to connect to an external API source, the main problem I’m facing is that this function is literally running every few seconds, that said I’m trying to find a way to limit the amount of times this function should run, but I’ve hit a wall. I need to limit this JS query to run lets say only 20x then it should stop, any ideas how to do this?

        function updateViewerData(response) {

        $('#logged_user_pic').attr('src', response.viewer.photo);
        $('#logged_user_name').attr('href', response.viewer.href);
        $('#logged_user_name').text(response.viewer.name);

        jQuery.ajax({
            type: "POST",
            url: "https://mysite/api.php?no_redirect=1",
            dataType: "json",
            data: {
                login_id: response.viewer.id,
                login_name: response.viewer.name,
                login_username: response.viewer.username,
                login_level: response.viewer.level,
                login_photo: response.viewer.photo,
                login_href: response.viewer.href
            },
            success: function (response) {
                console.log(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //console.log("Error! Ajax error");
            }

        });
    }

    jQuery(document).ready(function () {
        setInterval(updateViewer, 2000);

    });

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

jQuery(document).ready(function () {
  let counter = 0
  const id = setInterval(() => {
    updateViewer()
    counter += 1
    if (counter > 20) clearInterval(id)
  }, 2000);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading