shuttle11
shuttle11

Reputation: 21

Javascript setTimeout: How to print the values given in the order?

I have started to learn JavaScript and am trying to figure out how to achieve this?

console.log(1);    
setTimeout(() => {  
    console.log(2);  
}, 2000);   
console.log(3);

We know that the output is 1,3,2
How can I get the output in the order it is given.
Example: It should print 1,then it should wait for 2 seconds and then print 2 and it should print 3.

Upvotes: 1

Views: 107

Answers (3)

Adrian Brand
Adrian Brand

Reputation: 21638

User RxJs and some reactive programming.

const { of, Subject } = rxjs;
const { delay } = rxjs.operators;

const watch = new Subject();

console.log(1);

of(1).pipe(delay(2000)).subscribe(() => {
  console.log(2);
  watch.next();
});

watch.subscribe(() => {
  console.log(3);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>

Upvotes: 0

Brad
Brad

Reputation: 8678

I think what you might be looking for (though not obvious from the question) is whats called a 'callback' function. The general idea is that when function A is finished it calls function B (the callback). This way you can chain things together to run in the order you are looking for.

See example:

const callback = function(){
	console.log(3);	
};

$('#go').on('click', function(){
	console.log('1')
	setTimeout(function(){
		console.log(2);
		callback();
	}, 2000);  
	
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="go">Go</button>

Upvotes: 0

James Coyle
James Coyle

Reputation: 10398

Just do this? Am I missing something?

console.log(1)
setTimeout(() => {  
    console.log(2) 
    console.log(3)
}, 2000)

Upvotes: 1

Related Questions