-1
setInterval(()=>{
    for (j = 0; j < obj.length; j++) {
    }
})

I have this loop setup, is there any way to make the for loop go slower? obj length can be as big as 200-400 arrays. Jquery answers accepted.

messerbill
  • 5,499
  • 1
  • 27
  • 38
Xardas105
  • 85
  • 13
  • You do want to loop your loop like that with `setInterval`, right? – H.B. Mar 24 '18 at 14:21
  • What is the real problem you're having? Why would you want the loop to be slower? – JJJ Mar 24 '18 at 14:21
  • Yeah, I want setInterval on it. The problem is that I get very high cpu usage everytime the loop runs because it runs trought so many arrays at once every 2 sec. – Xardas105 Mar 24 '18 at 14:36

1 Answers1

3

Promise based delay:

const delay = x => new Promise(res => setTimeout(res, x));
(async () => {
    for (let j = 0; j < 10; j++) {
        console.log(j);

        await delay(1000);
    }
})();

(Furthermore, i believe that jQuery should never be used.)

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • @Ilyaskarim: No he/she's not. – H.B. Mar 24 '18 at 14:23
  • "Jquery answers accepted." at the last of question text. – Ilyas karim Mar 24 '18 at 14:24
  • 2
    @Ilyaskarim: That does not mean **only** Jquery answers accepted. Which would be utterly stupid. – H.B. Mar 24 '18 at 14:25
  • You can use delay function to delay the execution of code provided by jquery. – Ilyas karim Mar 24 '18 at 14:27
  • 1
    @Ilyaskarim: Or, you could just not. – H.B. Mar 24 '18 at 14:27
  • Can you just explain the promise part fast? If it's not too much work tho – Xardas105 Mar 24 '18 at 14:55
  • @Xardas105: `delay` creates a `Promise` that resolves (`res`) when the timeout ends. This then can be used in `async` functions with `await` to wait the given number of milliseconds. – H.B. Mar 24 '18 at 14:57
  • @Xardas105: Here would be links to introductions on [promises](https://developers.google.com/web/fundamentals/primers/promises) and [async functions](https://developers.google.com/web/fundamentals/primers/async-functions). – H.B. Mar 24 '18 at 14:58