0

I am using the Instagram API onto my website and need to grab only the first few words of the description of the first 8 pictures.

My problem is that if I try to take more than 11 words per picture, the page stops loading.

Here's my code:


success: function (data) {
            console.log(data);
            data.data.forEach(function (pic) {
                var height = pic.images.standard_resolution.height;
                var width = pic.images.standard_resolution.width;
                if (width == height && pic.type != "video") {
                    $("#img" + i).append("<img class='img-fluid' alt='placeholder' src=\"" + pic.images.standard_resolution.url + "\" > ");
                    var text = pic.caption.text;
                    var s = ""
                    var words = 0;
                    var j = 0;
                    while (words < 11 || j < text.length) {
                        if (text[j] == ' ') {
                            words++;
                        }
                        s += text[j];
                        j++;
                    }
                    $("#img" + i).append("<div class='mask flex-center waves-effect waves-light rgba-black-light'><p id='txt" + i + "' class='white-text'>" + s + "</p></div>");
                    i++;
                }
            });
        }

I don't really know what I am doing wrong and what could be so terrible about 8 more words (I only fetch 8 pictures).

Thank you in advance for looking at my problem.

Teelry
  • 13
  • 1
  • have you tried using the debugger and setting a breakpoint? – miThom Jul 18 '19 at 14:35
  • I haven't, I don't have anything that would allow me to but I don't think it would loop infinitely, I have checked the conditions a lot, even on paper – Teelry Jul 18 '19 at 14:43
  • There is a better way to get words than a loop..... simple reg exp split and slice https://stackoverflow.com/questions/18473326/javascript-break-sentence-by-words – epascarello Jul 18 '19 at 14:50
  • `"I am using the Instagram API onto my website".split(/\s/).slice(0,5).join(' ')` – epascarello Jul 18 '19 at 14:59

1 Answers1

2

Your while condition should be with an && instead of || like this while (words < 11 && j < text.length) otherwise you may reach the end of the sentence and still have not reached the max word count. Also you are missing a semicolon on var s = "";

To simplify your code, you can use the split method to get the number of words of a phrase. Ex:

var str = 'This is a random string';
var wordCount = str.split(' ').length;
David Fontes
  • 1,427
  • 2
  • 11
  • 16