J
J
JackShcherbakov2018-02-04 14:36:39
JavaScript
JackShcherbakov, 2018-02-04 14:36:39

Why does the callback fire earlier than it should?

Wrote the code https://codepen.io/CitizenOne/pen/qxZmoP
I'm trying to make the callback always run after the main function code. Callback should sort of wait.
What am I doing wrong? I, as in all articles on this topic, pass a function as an argument.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2018-02-04
@Minifets

Callback should sort of wait.

Why did you decide that the callback should wait?
In your case, you need either:
function callBack(func2){
  setTimeout(function(){
     console.log(1); 
     func2();
  }, 500);
}
callBack(function(){
  console.log(2);
});

Or like this:
function callBack(func2){
  console.log(1); 
  func2();
}
callBack(function(){
  console.log(2);
});

R
Rsa97, 2018-02-04
@Rsa97

And what's the problem, everything works exactly as you asked.
The callBack function sets a timer and calls the function passed to it as a parameter, 2 is output. After 500 milliseconds, the function passed in the timeout is called, 1 is output.

L
lavezzi1, 2018-02-04
@lavezzi1

I guess you wanted to do something like this: https://jsfiddle.net/w2md0h6j/2/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question