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?
2 Answers 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.
4 Comments
first does nothing except create the timer, it's unnecessary...Using setInterval() might be more appropriate: link
4 Comments
setInterval is almost never more appropriate.setInterval does not provide reliable timing when tabs are hidden, etc.
ifis satisfied"? How, the code doesn't do that. And you absolutely mustn't put your code into a busy loop waiting for it.