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.
Related
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();
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)
Can someone explain me, why if I create a function in JavaScript and add it to setTimeout, setTimeout doesn't work properly, but if I create anonymous function everything is okay? Example below:
It works:
setTimeout(function() {
alert("foo");
}, 100);
It doesn't works:
function foo() {
alert('foo');
}
setTimeout(foo, 100);
I checked your code, you are accessing snakeTail inside setTimeout callback. When callback function is executed after 100 ms the variable snakeTail is not available anymore. You should replace your line with
setTimeout(function(param){
alert("Game over! Your score: "+(param-5)+" points. Wanna play again?");
location.reload();
}, 100, snakeTail);
This way you can save the snaketail variable and pass it inside setTimeout callback.
Undersatanding setTimeout
There is no difference, how to use it, passing anonymous function to setTimeout:
setTimeout(function() {
console.log("foo");
}, 1000);
Or passing an existing function:
function foo() {
console.log('foo');
}
setTimeout(foo, 1000);
setTimeout is an asynchronous, so if you will use it before the regular console.log, the console.log after setTimeout function will be printed first, and then, the console.log inside setTimeout will be printed after specified delay (1 second in this case):
setTimeout(function() {
console.log("bar");
}, 1000);
console.log("foo");
But if you want to log "foo" after 1 second and then to log "bar" after one second from "foo" was logged, you can add 2 second delay to the second setTimeout, like this:
setTimeout(function() {
console.log("foo");
}, 1000);
function bar() {
console.log('bar');
}
setTimeout(bar, 2000);
Or alternatively you can wrap one setTimeout into another and give both of the 1 second delay. In this case, after 1 second will be printed "foo", and after 2 seconds will be printed "bar":
setTimeout(function() {
console.log("foo");
setTimeout(bar, 1000);
}, 1000);
function bar() {
console.log('bar');
}
Hope this will give you the basic understanding of how setTimeout works.
I want to know how to make setTimeout wait before executing what comes after.
setTimeout( function() { console.log("First"); }, 5000 );
console.log("Second");
In the console I want to see:
First
Second
"First" after 5 seconds and then "Second" just after "First"
But what's really happening is that I have "Second" and after 5 seconds "First"
How can this be fixed ?
If IE is not priority and you allowed to use Promise, then you can use a simple wait function to work as setTimeout and return Promisewhich allows for method chaining:
function wait(t) {
return new Promise(function(resolve) {
window.setTimeout(resolve, t)
});
}
wait(5000)
.then(function(){ console.log("First"); })
.then(function(){ console.log("Second"); });
setTimeout( function() { console.log("First"); }, 1000 );
setTimeout( function() { console.log("Second"); }, 1000 );
Javascript does not guarantee linear order of execution in your code. You can't expect your code to execute line by line when introducing timeouts or asynchronous tasks.
You could print both lines within the resolving function:
setTimeout(function() {
console.log("First");
console.log("Second");
}, 5000);
If you are executing more than just a console log after, you can write a new function to run after the setTimeout. Anything in the "second" function will occur after logging "First".
var second = function () {
console.log("Second");
}
setTimeout( function() {
console.log("First");
second();
}, 5000 );
I want to know how to make setTimeout wait before executing what comes after.
I think the JavaScript function for "wait" is setTimeout. Meaning you can achieve this by nesting one setTimeout function inside another.
setTimeout(function() {
setTimeout(function() {
console.log('Second');
}, 100);
console.log('First');
}, 5000);
I have a question about javascript function sequence,I have two code below,Why the different results of these two programs?
I think first program result will equal to second program result.
function test1() {
for (var i = 1; i <= 1000000; i++) {
}
console.log("test1");
}
function test2() {
console.log("test2");
}
test1();
test2();
//test1
//test2
function test1() {
setTimeout(function() {
console.log("test1");
}, 1000);
}
function test2() {
console.log("test2");
}
test1();
test2();
//test2
//test1
Because the purpose of setTimeout (MDN | spec) is to schedule a call to a function later, asynchronously. So in your second example, you call test1 first, and it schedules a call to the anonymous callback for a second later, then returns. Then you call test2 which prints immediately. A second later, the callback is called by the timer, and prints test1.
Perhaps this small tweak to your second example will make it clearer:
function test1() {
console.log("test1 called, setting up timer");
setTimeout(function() {
console.log("timer fired and called the callback");
}, 1000);
}
function test2() {
console.log("test2 called");
}
test1();
test2();
You see this output (the last line only appears after a second):
test1 called, setting up timer
test2 called
timer fired and called the callback
setTimeout is an asynchronous operation , the number is use to define delay at which the code will execute. 1000 is the delay, so you are seeing the result differently
http://javascript.info/tutorial/settimeout-setinterval
check this out
mabe it will help :)
In my opinion, maybe your current thread got stuck in the "for" loop in your first code snippet. But the operation is asynchronously done in the second code snippet.