Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

javascript - callback gets called before rest of the function executed

I recreated this example (from link given below) to understand callbacks. The problem is that the callback gets executed before the parent function 'first()' finishes. setTimeout works fine but callback doesn't wait until after the above . If i comment out line 1 and 3 of first() i.e. the timeout part, then it logs in the right order.

<script type="text/javascript">
function second() {
    console.log("second/callback function")
}

function first(callback){
    setTimeout(function(){
        console.log("first function")
    }, 1000 );
    callback();
}

first(second);

If this is working fine and i misunderstand the nature of setTimeout, then please give another example where the callback can be seen waiting.
Link: https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced
Note: I know very little JS, was actually working in PHP, so kindly give a simple explanation. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It appears that you misunderstand how setTimeout() works. This tool called Loupe by Philip Roberts may help you understand. I've taken your code placed it into the tool which will allow you to visualise what is actually happening - link to Loupe

When you use setTimeout, that function provided as the first parameter is delayed for the number of milliseconds provided in the second parameter (in your example, this is 1000). The rest of your code will continue to execute in order until this timeout has lapsed.

If you want your callback function to execute after the given timeout: you can actually just write it such like:

setTimeout(callback, 1000) <- Since callback is already a function, you don't need to wrap it in another function unless you wish to do other operations before calling the callback.


Update 1 (2018-10-26):

function second() {
    console.log("second/callback function")
}

function first(callback){
    console.log("first function")
    setTimeout(callback, 1000);
}

first(second);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...