-3

Hello I am making an for loop to get data from iframe. But the loop is too fast. How can i slow down this loop to execute every iteration in 50-100 ms or more?

        for (let i = 113361978; i < 113371978; i++) {

        fetch('https://vimeo.com/api/oembed.json?url=https://player.vimeo.com/video/' + i)
        .then(res => res.json())
        .then(
            (json) => {
                console.log(i);
                if (json.author_name === 'Chuck Norris') {
                    document.write(`<iframe src="https://player.vimeo.com/video/${i}" width="640" height="640" frameborder="0" allowfullscreen=""></iframe>`);
                }   
            }
        )
    }

I tried also using setInterval but then my i variable doesnt equal to result and display iframe with wrong id.

                let i = 220316094;
                function loop(){

                    fetch('https://vimeo.com/api/oembed.json?url=https://player.vimeo.com/video/' + i)
                        .then(res => res.json())
                        .then(
                            (json) => {
                                console.log(i);
                                if (json.author_name === 'Chuck Norris') {
                                    document.write(`<iframe src="https://player.vimeo.com/video/${i}" width="640" height="640" frameborder="0" allowfullscreen=""></iframe>`);
                                }

                            }
                        ).then(i++) 
                }

                function loop2(){
                    setInterval(loop, 50);
                }
                loop2()
sherlok222
  • 41
  • 6
  • Isn't the document.write overwriting the entire page? I don't see the documentation for vimemo.com/api at vimeo.com/api but they should not be suggesting that as the proper coding ... even just changing the src for the iframe is going to have performance issues. as each frame would begin a new connection. – Wayne May 19 '19 at 22:44

1 Answers1

1

Embrace async and await for easier to follow asynchronous code.

Now you can rewrite your function as

async function doTheDownloads(){
    for (let i = 113361978; i < 113371978; i++) {
        const url = 
          'https://vimeo.com/api/oembed.json?url=https://player.vimeo.com/video/' + i
        const res = await fetch(url)
        const json = await res.json()
        if (json.author_name === 'Chuck Norris') {
            document.write(something); //you probably want a different approach here
        } 
    }
}

Now define an async delay function

const delay = t => new Promise(resolve => setTimeout(resolve, t))

and use it in the loop

async function doTheDownloads(){
    for (let i = 113361978; i < 113371978; i++) {
        const url = 
          'https://vimeo.com/api/oembed.json?url=https://player.vimeo.com/video/' + i
        const res = await fetch(url)
        const json = await res.json()
        if (json.author_name === 'Chuck Norris') {
            document.write(something); //you probably want a different approach here
        } 
        await delay(1000) //wait for 1s
    }
}

const delay = t => new Promise(resolve => setTimeout(resolve, t))
async function doTheDownloads(){
    for (let i = 113361978; i < 113371978; i++) {
        const url = 
          'https://vimeo.com/api/oembed.json?url=https://player.vimeo.com/video/' + i
        const res = await fetch(url)
        const json = await res.json()
        const el = document.body.innerHTML += json.html
        await delay(1000) //wait for 1s
        
        break; // <= remove this
    }
}
doTheDownloads()
spender
  • 117,338
  • 33
  • 229
  • 351
  • delay is not defined ah ok will try – sherlok222 May 19 '19 at 22:49
  • @sherlok222 Did you read all of my answer? You need to define `delay` as described. – spender May 19 '19 at 22:50
  • yes but the if condition in document write now doesnt work :/ if (json.author_name === 'Chuck Norris') { Thats why i used .then promise – sherlok222 May 19 '19 at 23:01
  • @sherlok222 That's a different question, but frankly, I'm surprised it worked in the first place. If you want to add stuff to an existing document, `document.write` is the wrong tool for the job. You'd want something like `const el = document.createElement("iframe"); el.setAttribute("src", someUrl); document.body.appendChild(el);` . Don't turn this into a chameleon question. The issue you asked about in your question is solved. – spender May 19 '19 at 23:07
  • the write is ok for me, just for testing. The problem is Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 4 and idk why you used const for url – sherlok222 May 19 '19 at 23:11
  • @sherlok222 That's a completely different issue and can't be solved here in the comments section. I used `const` because it's the appropriate way to declare a variable that won't change within the scope that it's defined. `var` is old-school, and if possible should be replaced by either `let` or `const` in new code. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const – spender May 19 '19 at 23:16
  • @sherlok222 The error you are seeing is because whatever you downloaded isn't JSON. That's what the error tells you. Developer tools of your browser will help you establish what was downloaded. – spender May 19 '19 at 23:18
  • dammit looks like someone blocked it right now O_O after post this question, joke it works try my first code you can execute it in the browser and check but you need to change the id range and name of the author or check this and you see there is json ```fetch('https://vimeo.com/api/oembed.json?url=https://player.vimeo.com/video/220321193') .then(res => res.json()) .then(console.log)``` – sherlok222 May 19 '19 at 23:21
  • ...but your code doesn't work. Mine does. I inserted a ***working*** snippet for you to run that should hopefully get you on your way. – spender May 19 '19 at 23:33
  • using .then promises output the json and allow to manipulate on it my first code worked with if condition. but i will try your update you added await – sherlok222 May 19 '19 at 23:38
  • @sherlok222 Sorry about the typos. The snippet works 100% now, but I break on the first iteration. – spender May 19 '19 at 23:40
  • no your code doesn't work. It works only for first element. It does not working on iterations. that's the problem. Check my first code you can delete if statement or replace it and check how it should work but reduce range – sherlok222 May 19 '19 at 23:46
  • I've tried to tell you a long time ago that the remaining problems in your code are ***new*** questions, and shouldn't be answered in the comment section. The code doesn't work because video `113361979` returns `403 Forbidden`, which you failed to check because you have no error checking. ***Your original question is ANSWERED*** If you're still stuck, ***ask a new question***. – spender May 19 '19 at 23:50
  • ok i will not spam here. It doesnt matter if it return 403 or 404 loop goes further and display working videos based on condition with json which your code doesnt provide and your code return Uncaught (in promise) SyntaxError: Unexpected token F in JSON – sherlok222 May 19 '19 at 23:52
  • @sherlok222 Sure your code moves on, because you launch all `fetch` at the same time (the fetches will happen all in one go, after your javascript has finished running, probably [something like 6-8 at a time](https://stackoverflow.com/questions/985431/max-parallel-http-connections-in-a-browser)). You asked how to slow things down, which is now solved. You can't have both of these "features". You need to catch the errors. Simple. – spender May 19 '19 at 23:56
  • https://stackoverflow.com/questions/56212959/after-function-slow-down-there-is-no-working-condition-for-json – sherlok222 May 20 '19 at 00:02
  • using async await is ok but the question was how to slow down loop with promises so your code just doesnt work, you provide general solutions which doesnt work in case of the thread. otherwise i will not put code here and the category of this ask is to help with code thanks anyway – sherlok222 May 20 '19 at 00:08
  • Your resistance to the correct way of solving this is incredible. I'm holding up a light and you're telling me that it's the wrong kind of light. async/await *is* promises, you just don't understand them properly. – spender May 20 '19 at 00:19
  • Seems like you are new to javascript, thats ok me too. but please care twice before you put thing in the wrong way. – sherlok222 May 20 '19 at 00:23