简体   繁体   English

Javascript自定义回调函数

[英]Javascript Custom Callback Function

I have one concern about javascript callback function. 我担心javascript回调函数。 What I understood is callback function should allow other statements to proceed if it takes time. 我了解的是,如果需要时间,回调函数应允许其他语句继续执行。 So I have created one custom callback function to check but I'm not getting expected result. 因此,我创建了一个自定义回调函数进行检查,但没有得到预期的结果。 Am I doing wrong anything here? 我在这里做错什么吗?

 function test(param1,param2,cb){ if(typeof(cb) === 'function') return cb(param1,param2) else console.log('im not a func'); } function calbackFunc(a,b){ console.log('Hi i am '+a+' '+b); } setTimeout(function timeout(){ console.log('timeout') },0); test('callback','function',calbackFunc); console.log('console'); 

Output 产量

"Hi I am callback function" “嗨,我是回调函数”

"console" “安慰”

"timeout" “暂停”

As per the callback function, 'console' should come first. 根据回调函数,“控制台”应排在首位。 but it's not happening. 但是这没有发生。 Like setTimeout is working fine. 就像setTimeout正常工作一样。 Then why my custom callback function behaving like setTimeout. 那为什么我的自定义回调函数表现得像setTimeout。

You're getting confused between the Stack and the Queue . 您对StackQueue感到困惑。

The Event Loop 事件循环

In javascript , synchronous calls are going into the stack while asynchronous calls are going into the Heap , and when done are back in the Queue . javascript中 ,同步调用进入堆栈,而异步调用进入 ,完成时返回队列 A function is moving from the Queue to the Stack only when it's empty. 仅当函数为空时,它才从队列移至堆栈

在此处输入图片说明

In your example 在你的例子中

phase 1: call setTimeout() 阶段1:调用setTimeout()

this puts the function in the heap , and since the timeout is set to 0, it right away moves to the _queue. 这会将函数放入堆中 ,并且由于超时设置为0,因此它将立即移至_queue。 does it means that it's executing right away? 这是否意味着它立即执行? no, because that your current function (the "main") hasn't finished yet. 不,因为您当前的功能(“主”)尚未完成。

phase 2: call test() 阶段2:呼叫test()

this code is synchronous ! 此代码是同步的 when calling test we add a function to the stack . 调用test我们将一个函数添加到堆栈中 then we add the cb() call to the stack . 然后我们将cb()调用添加到堆栈中 that means that we need to finish all both before we can proceed to phase 3. 这意味着我们需要先完成所有这两项工作,然后才能进入第3阶段。

phase 3: console.log 阶段3: console.log

nothing to explain here 这里没什么可解释的

post phase 3 第三阶段

the current "main stack is finished, so the function from the queue is now added ti the stack , logging 'timeout' . 当前的“主堆栈已完成,因此现在将队列中的函数添加到堆栈中 ,并记录'timeout'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM