On Jan 3, 2015, at 10:25 AM, schone wrote:
> 
> I'm trying to wait or sleep a fixed amount of time inside a while and/or for 
> loop in node.js (I'm trying to mimic delayed random data). As an example, I 
> have the following structure:
> 
> var startIndex = 0,
>     endIndex = 10,
>     incrementIndex = 1;
> while ( startIndex < endIndex ) {
> 
>   for ( var i = 0; i < array.length; i++ ) {
>     // do stuff
>     // sleep here?
>   }
>   // do stuff
>   startIndex = startIndex + incrementIndex;
>   // sleep here?
> }
> 
> Has anyone got any tips for how you would implement a setTimeout or similar 
> function in node.js with the above structure?

You are trying to write synchronous code. Don't. Write asynchronous code. Use 
the built-in JavaScript setTimeout function, etc. If you are trying to simulate 
data arriving from an external service after an unpredictable delay, that data 
will certainly arrive asynchronously as well. Your current code tries to 
process all the data at once. Rewrite your code so that you have a 
self-contained function that can process a single unit of work, then arrange to 
call that function whenever the data arrives (or is simulated to arrive).



-- 
Job board: http://jobs.nodejs.org/
New group rules: 
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/nodejs/C474281A-722D-46FE-B738-48941BB5CEBA%40ryandesign.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to