Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

117
Views
observable - how do I return values using forEach and setTimeout? (nothing to do with Rxjs)

I'm new to observablehq notebook. I found this is very helpful tool for me to prototype my visuals.

My question is How do I iterate an array and return values with setTimeout of javascript?

My approach is as below.

  1. array is declared

    arr = [1,2,3,4,5]

  2. iterate the array and return values

       arr.forEach((d,i)=>{
     setTimeout(()=>{
       return d
     },i*1000)})
    

How do I achieve this?

I saw similar posting using Rxjs but I don't use that. Is there a basic / elementary way of achieving this?

I think the reason that this isn't working is something to do with closure. But can't think of solving the issue.

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

You can try the solution below

    myArr = [1, 2, 3, 4, 5];

//Now, iterate over the array with setTimeout
myArr.forEach(function(d, i) {
    setTimeout(function() {
        console.log(d);
        return d;
    }, 1000 * i);
});
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs