A
A
akdes2017-07-13 18:37:49
JavaScript
akdes, 2017-07-13 18:37:49

Asynchronous array processing with a timer, why doesn't it work?

Hi all.
There is a need to process an array asynchronously, with a delay.
I made a fiddle that clearly shows the problem:
https://jsfiddle.net/akdes/20he422s/
According to my idea, with zero delay, I should write to the console the text from the first array "foo" and only after 2 seconds "bar"
What I'm doing wrong ? how to solve the problem?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2017-07-13
@akdes

Everything is made easier:

var items = [
{
  text: "foo",
  delay: 0
},
{
  text: "bar",
  delay: 2000
}];

printAsync();
function printAsync() {
  var delay = 0;
  items.forEach(item=>setTimeout(function() {
    console.log(item.text)
  }, item.delay))
}
https://jsfiddle.net/ddo259tv/
You don't have anything asynchronous in your code other than calling setTimeout, which is a hundred years old at noon. And you didn’t understand the meaning of the new word async from es8.

O
olezhenka, 2017-07-13
@olezhenka

Will such a recursive function work?

var textArray  = [{
  "text": "foo",
  "delay" : "2000"
},
{
  "text": "bar",
  "delay" : "2000"
}];
(function one(i) {
  console.log(textArray[i].text);
  setTimeout(function() {
  	one(i+1);
  }, textArray[i].delay)
})(0);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question