Home > Enterprise >  Limit JavaScript to run X amount of times
Limit JavaScript to run X amount of times

Time:09-14

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);

    });

CodePudding user response:

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