Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am being given the below mentioned code and asked to print the console after 3 seconds - B and C after A.
I tried
setTimeout(main(),3000);
But I get no output.
function sleep(){
}
function main(){
console.log('A');
// call after 3 sec
console.log('B');
// call after 3 sec
console.log('C');
}
}
setTimeout(main , 3000);
remove function call '( )'
How setTimeout works:
You specify the function (as a first argument) to be called after your timeout (second argument: 3000)
Generally you should pass the function by name to the setTimeout function without calling it.
setTimeout(main,3000);
setTimeout(main(), 3000) will execute main immediately because you put the () after it. Just use the name. setTimeout(main, 3000)
Also, you'll want to put your timeout on the two specific log statements you want to call later, not the whole function, or you could also log A outside of the main function and then call the main function after the timeout.
function main() {
console.log('A');
// call after 3 sec
setTimeout(() => {
console.log('B');
console.log('C');
}, 3000);
}
main();
try this
setTimeout(main,3000);
function main(a){
console.log('A');
setTimeout(function(){
console.log('B');
setTimeout(function(){
console.log('C');
}, 3000);
}, 3000);
}
You are calling the function in the first parameter of setTimeout. It is supposed to be a callback function(function definition). Just copy the code of the main function inside the setTimeout function and it will work.
The setTimeout Function is used usually with two parameters.
The callback function
Time in milliseconds
The callback function is called after a given time (second param).
This is how it is called:
const callbackFunction = () =>{
console.log("Inside callback");
}
setTimeout(callbackFunction, 2000);
OR simply
setTimeout(() =>{
console.log("Inside callback");
}, 2000);
Output (after 2 secs)
Inside callback
Above output could also be reproduced using async-await:
function sleep(time) {
return new Promise(resolve => {
setTimeout(() => {
resolve("");
}, time);
});
}
async function main() {
await sleep(0);
console.log('A');
// call after 3 sec
await sleep(3000);
console.log('B');
// call after 3 sec
await sleep(3000);
console.log('C');
}
main();
Related
This snippet logs 'output 2' ahead of 'output 1', which is cool due to the setTimeout.
const func1 = () => {
setTimeout(() => {
console.log('output 1');
}, 3000);
};
const func2 = () => {
console.log('output 2');
};
func1();
func2();
In this snippet, I used a callback, but it gave me the same result as the last snippet, why doesn't func1 execute before func2? How can I make func2 execute after func1?
const func1 = () => {
setTimeout(() => {
console.log('output 1');
}, 3000);
};
const func2 = () => {
console.log('output 2');
};
const main = (a, b) => {
a();
b();
};
main(func1, func2);
why doesn't func1 execute before func2
It does.
Func1 sets a timeout running
Func2 logs
3 seconds later the callback function you pass to setTimeout is called
If you want to make Func2 run after step 3, then you need to call it at the end of the callback you pass to setTimeout.
JavaScript does not wait for setTimeout to finish and then execute next functions.
whenvever javascript encounters a setTimeOut it store functions with provided timeout, in this case 3 seconds. after storing it in call stack it just starts to execute functions below it and since there is nothing in second function it get executed right away ( before 3 seconds obviously ). that's why you are seeing the log of second function before the log of first function.
To execute first function and then execute second function you can use promise chaining.
Example:
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log('output 1');
resolve();
}, 3000);
}).then(function(result) {
console.log('output 2');
});
Hope it will help. Feel free to correct if i am wrong.
Simple explanation -
Function 2 wouldn't wait for the completion of the timer started in function 1.
func1();
func2();
When you execute both functions, function 1 sets the timer and function 2 logs out.
Eventually, function 1 logs out after 3 seconds.
Your second snippet does pretty much the same.
I have some code which can be mimicked by this situation
function abc(def){
setTimeout(1500,function(){
console.log('1');
}
def();
}
function def(){
console.log('2'}
}
I want 2 to be printed after 1 - how do I do that?
If you want a function to also be called after a delay... just put it inside the delay. I've added some extra console logs and fixed some of your code. Run the below example to see how it works.
function def() {
console.log('2 - def()');
}
function abc() {
console.log('before');
setTimeout(function() {
console.log('1');
def();
}, 1500);
console.log('after');
}
abc();
function abc(def){
setTimeout(1500,function(){
console.log('1');
def();
}
}
You can use async and await. Wrap the setTimeout(...) in a Promise and resolve Promise inside the callback passed to setTimeout.
async function abc(def){
await new Promise(res => {
setTimeout(function(){
console.log('1');
res();
},1500)
})
def();
}
function def(){
console.log('2')
}
abc(def)
setTimeout(function, milliseconds) takes a function has the first parameter and delay value (time in milliseconds) as the second parameter. You were passing them in the wrong order.
Also in your example def() was printing 2 and it was outside the setTimeout function, so it could not have possibly printed 2 after 1 (as 1 was being logged inside the setTimeout, which means it would be executed after the delay of 1.5 seconds).
The solution provided by Chris above is correct and would do what you wanted (print 2 and then 1)
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have 2 separate functions, both are making a GET request.
After completing, I need to add up number from response1 with number from response2. So basically I want make 3rd function, that will add up results from previous 2 functions.
The problem is that 3rd function executes before 1st and 2nd.
I tried callbacks, but seems it's not working as expected. Below you can find a simple example and I want to understand the basics before implementing it in my code. Example with callback I tried:
function first(callback){
setTimeout(function(){
console.log(1);
}, 500);
callback()
}
function second(){
console.log(2);
}
function third(){
first(second);
}
third();
Example without callback:
function first(){
setTimeout(function(){
console.log(1);
}, 500);
}
function second(){
console.log(2);
}
function third(){
first();
second();
}
third();
https://jsfiddle.net/u8a592pz/
Currently this function executes as:
2
1
What I want to get:
1
2
Wrap the content of first in a Promise and return it. And make third as async function and use await before first()
function first(){
return new Promise(res => {
setTimeout(function(){
console.log(1);
res();
}, 500);
})
}
function second(){
console.log(2);
}
async function third(){
await first();
second();
}
third();
So I was doing some practice about callback function and I wanted to try it out in my own was and use it with a setTimeout Method and to my surprise, it didn't work as expected.. Pls what am i doing wrong here.
function first(number, callback) {
setTimeout(function() {
console.log(number);
}, 5);
callback();
}
function second() {
console.log(2);
}
first(1, second);
You're executing setTimeout and callback at the same time. Because JavaScript is single-threaded, it doesn't wait for setTimeout to complete before executing the next statement.
That's why, 2 prints immediately, and then 1 prints after a delay of 5 milliseconds.
If you want to print 1 first, then you need to call the callback function in the callback of setTimeout. This ensures that the console.log(number) executes prior to calling the callback (which prints 2).
function first(number, callback) {
setTimeout(function() {
console.log(number);
callback();
}, 5);
}
function second() {
console.log(2);
}
first(1, second);
As 31piy already said, setTimeout() and callback() are being executed at the same time. Your code first schedules a function execution at 5ms from now, and then immediately runs another function that logs 2 to the console.
You can achieve the expected result in a couple of similar ways, I'll show one:
function first(number,callback) {
setTimeout(function() {
callback();
}, 5);
console.log(number);
}
function second() {
console.log(2);
}
first(1, second);
//Here, you immediately print the number 1 and schedule the number 2.
I have the following scenario:
setTimeout("alert('this alert is timedout and should be the first');", 5000);
alert("this should be the second one");
I need the code after the setTimeout to be executed after the code in the setTimeout is executed. Since the code that comes after the setTimeout is not code of my own I can't put it in the function called in the setTimeout...
Is there any way around this?
Is the code contained in a function?
function test() {
setTimeout(...);
// code that you cannot modify?
}
In that case, you could prevent the function from further execution, and then run it again:
function test(flag) {
if(!flag) {
setTimeout(function() {
alert();
test(true);
}, 5000);
return;
}
// code that you cannot modify
}
I came in a situation where I needed a similar functionality last week and it made me think of this post. Basically I think the "Busy Waiting" to which #AndreKR refers, would be a suitable solution in a lot of situations. Below is the code I used to hog up the browser and force a wait condition.
function pause(milliseconds) {
var dt = new Date();
while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}
document.write("first statement");
alert("first statement");
pause(3000);
document.write("<br />3 seconds");
alert("paused for 3 seconds");
Keep in mind that this code acutally holds up your browser.
Hope it helps anyone.
Using ES6 & promises & async you can achieve running things synchronously.
So what is the code doing?
1. Calls setTimeOut 1st inside of demo then put it into the webApi Stack
2. Creates a promise from the sleep function using the setTimeout, then resolves after the timeout has been completed;
3. By then, the first setTimeout will reach its timer and execute from webApi stack.
4. Then following, the remaining alert will show up.
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
setTimeout("alert('this alert is timedout and should be the first');", 5000);
await sleep(5000);
alert('this should be the second one');
}
demo();
Just put it inside the callback:
setTimeout(function() {
alert('this alert is timedout and should be the first');
alert('this should be the second one');
}, 5000);
No, as there is no delay function in Javascript, there is no way to do this other than busy waiting (which would lock up the browser).
ES6 (busy waiting)
const delay = (ms) => {
const startPoint = new Date().getTime()
while (new Date().getTime() - startPoint <= ms) {/* wait */}
}
usage:
delay(1000)
You can create a promise and await for its fulfillment
const timeOut = (secs) => new Promise((res) => setTimeout(res, secs * 1000));
await timeOut(1000)
Here's a good way to make synchronous delay in your code:
async function yourFunction() {
//your code
await delay(n);
//your code
}
function delay(n) {
n = n || 2000;
return new Promise(done => {
setTimeout(() => {
done();
}, n);
});
}
Found it here Right way of delaying execution synchronously in JavaScript without using Loops or Timeouts!
setTimeout(function() {
yourCode(); // alert('this alert is timedout and should be the first');
otherCode(); // alert("this should be the second one");
}, 5000);
I think you have to make a promise and then use a .then() so that you can chain your code together. you should look at this article https://developers.google.com/web/fundamentals/primers/promises
You could attempt to replace window.setTimeout with your own function, like so
window.setTimeout = function(func, timeout) {
func();
}
Which may or may not work properly at all. Besides this, your only option would be to change the original code (which you said you couldn't do)
Bear in mind, changing native functions like this is not exactly a very optimal approach.