Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

I'm Experimenting with settimeouts and i'm stuck trying not to DRY.

https://w.trhou.se/0x8a13medi Been told before to gain experience so I'm experimenting. Got problems at line 40 any suggestions please.

Thank You.

3 Answers

Steven Parker
Steven Parker
231,248 Points

The program defines nameId but never calls it.

But the issue is that the loop starts 3 timers that all have the same delay, so they all go off at once. One way to get them to go off sequentially would be to increase the time for each one:

        for (let i = 0; i < 3; i++) {
            setTimeout(() => { 
                console.log(i + "Accessing...");
            }, 1500 * i);        // <-- NOTE: time is increased for each one
        }

But your comment says "without repeating settimeout", so perhaps what you have in mind would be to replace the loop with a function that sets a timer to call itself the appropriate number of times:

        let timer = () => {
            console.log(i + "Accessing..."); 
            if (++i < 3)
                setTimeout(() => { timer(); }, 1500);  // set a timer to call itself
        }
        let i = 0;
        timer();  // call it the first time manually

oh I was close, I didn't think to submit ( i ) into console.log( i + "Accessing..." ).
Ultimately I wanted:-
Accessing..
Accessing...
Accessing....
(Increasing the dots .. ... ....)
To make it appear to the user that there was thought behind the process, I dont think I can achieve this without repeating code...?

Thanks for your last reply though... your answer is thought provoking..

Steven Parker
Steven Parker
231,248 Points

You can do this with either of the above methods, just substitute the log statement with this:

            console.log("Accessing.." + ".".repeat(i));

How would you know that? wow It's like you escaped the matrix and learnt everything!!!

Seriously though thanks, just hope I can retain more and more knowledge.

Steven Parker
Steven Parker
231,248 Points

It's just lots of practice (over 10 years in my case).   :wink: