0

I have two functions in Javascript code one looped in the other.

Something like:

function doThis(){
 doThat(); 
 window.setTimeout( doThis , 2000); 
}
function doThat(){
 if(someCondition){
 window.clearTimeout(id)
 }
 var id = window.setTimeout( doThat, 10000);
}

What exactly I want to do: doThis is called as soon as the window is loaded. Now, as soon as it is called, it should hand over the control to doThat() which waits for 10 seconds before executing again.

Now, doThat() is executed till the if codition is satisfied. And then, it should hand the control back to doThis() which should then wait for 2 seconds and repeat this cycle over and over.

I do not want to use jQuery(callback or chaining stuff) or any other javaScript libarary.How to do this?

flavian
28.6k11 gold badges68 silver badges107 bronze badges
asked May 12, 2013 at 11:30
1
  • 1
    "executed till the if is satisfied"? How, the code doesn't do that. And you absolutely mustn't put your code into a busy loop waiting for it. Commented May 12, 2013 at 11:37

2 Answers 2

2

If I understood correctly,

function first() {
 setTimeout(second, 1000)
}
function second() {
 if(condition) {
 setTimeout(first, 2000)
 } else {
 setTimeout(second, 10000)
 }
}

No need to save the timeout anywhere or to clear it.

answered May 12, 2013 at 11:37
Sign up to request clarification or add additional context in comments.

4 Comments

in 'first()', you did 'setTimeout(second, 1000)'. Could you please explain me what is that for? I will lose 1 second for no reason. Isn't it?
@NavneetSaini: I misread your explanation then. It would help if you provided your actual code, because currently the first function makes no sense at all.
I got an idea how to do it, if it doesnt work, I will return back. Thanks for your response:)
of course, if first does nothing except create the timer, it's unnecessary...
0

Using setInterval() might be more appropriate: link

answered May 12, 2013 at 11:33

4 Comments

using setInterval is almost never more appropriate.
@Alnitak What do you mean?
@NavneetSaini because setInterval does not provide reliable timing when tabs are hidden, etc.
@Alnitak, so what could be the better way to execute above thing, then?

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.