1

Good day all.

I have this simple code:

totalTextArray = textForChatWithSeparators.split("#"); 
 $.each(totalTextArray, function( index, value ) { 
 setTimeout(function(){console.log( value )},1000);
});

I expect to see in the console log, every second, the "value" logged, but instead I see all the log coming out in one block, after the delay of 1 second.

what i'm doing wrong? I'm thinking of the fact that a function inside the function could lead to some buffering problem?

asked May 20, 2014 at 9:41
1
  • Use (index + 1) * 1000 instead of 1000 Commented May 20, 2014 at 9:42

2 Answers 2

4

What you're doing is

  • make a call to setTimeout n times
  • all timeouts will fire after 1000ms together

What you would need to do if you don't want to change the structure is to increase the timeout value per iteration, like

setTimeout(function(){ console.log( value ) },1000*index);

A probably more elegant (and more correct way imo), would be to change the structure of the loop all together. Using an interval-timer like

(function _loop( elem ) {
 console.log( elem ); 
 if( totalTextArray.length ) {
 setTimeout( _loop.bind( null, totalTextArray.shift() ), 1000 );
 }
}());
answered May 20, 2014 at 9:43
Sign up to request clarification or add additional context in comments.

1 Comment

you are right, i simply condensed all the timeouts after the 1st second. Thanks!
1

All you need is closure:

totalTextArray = textForChatWithSeparators.split("#");
$.each(totalTextArray, function(value, index) {
 setTimeout(function() {
 console.log(value);
 }, 1000 * (index + 1));
});

EDIT: I add more links about closure:

answered May 20, 2014 at 9:43

5 Comments

I think you've misread the question. The issue is that the timeouts all fire at the same time.
Sorry, I forgot to add the index to interval time :|
But without using clousre, I am sure the value in log is wrong.
No, in this case since we already have a function-loop, we don't need to create another context. The anonymous loop function itself will create a new one per iteration.
Yep, I've just realized that. Thank you!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.