简体   繁体   English

如果在JavaScript中单击按钮事件时调用两个函数会发生什么

[英]What happens if call two functions when button click event in javaScript

I'm tying to call two functions in JavaScript when a button click event happens. 当发生按钮单击事件时,我想在JavaScript中调用两个函数。

<button type="submit" id="mySubmit" onClick="submitInput();getAll()">Search</button>

So I wondered what function will call first. 所以我想知道首先调用什么函数。 And I have no idea. 我不知道。

Will the submitInput() executes first or getAll() or both executes at the same time concurrently. 将首先执行submitInput()getAll()还是两者同时执行。 ?

It executes the same way as ordinary javascript. 它执行与普通javascript相同的方式。 submitInput() executes first. submitInput()执行submitInput() I would not reccomend doing it this way though. 我不建议这样做。 It would be considered bad practice. 这将被视为不良做法。 keep your javascript out of your HTML ok. 将您的JavaScript保留在HTML之外。

Lastly, just because something executes first, does not mean that it will finish first.. javascript is both async and synchronous in some cases. 最后,仅因为某事首先执行,并不意味着它会先完成。在某些情况下,javascript是异步的还是同步的。

JavaScript is by nature mono-thread, that is to say its engine can only compute one operation at once (it is not parallel !). JavaScript本质上是单线程的,也就是说它的引擎只能一次计算一个操作(不是并行的!)。 It means that as long as a process is not finished, the user remains stuck in front of his browser and has to wait till the end. 这意味着只要一个过程还没有完成,用户就一直停留在浏览器的前面,必须等到最后。 Theoritically :) 理论上:)

Fortunately, JS is also asynchronous, it means that one is able to free the user thread, waiting for some other conditions to be fullfilled to continue the computation. 幸运的是,JS也是异步的,这意味着它可以释放用户线程,等待其他条件满足后才能继续计算。 To be more accurate, the execution of some functions can be delayed, one of the simplest examples is the use of the functions setTimeout() (once) or setInterval() (several times). 为了更准确,可以延迟某些函数的执行,最简单的示例之一是使用setTimeout()(一次)或setInterval()(多次)的功能。 A callback is a function triggered only under some conditions (ie a time interval expires, a script sends an answer, etc...). 回调是仅在某些情况下(即,时间间隔到期,脚本发送答案等)触发的函数。 It prevents the browser from being "freezed", waiting for the result of a computation. 它防止浏览器被“冻结”,以等待计算结果。

In your case, if there isn't any asynchronous call, the functions will be executed in the order you gave. 在您的情况下,如果没有任何异步调用,则函数将按照您指定的顺序执行。 Once the first is completed, the second will be triggered. 一旦第一个完成,将触发第二个。

Try those two dummy functions : 试试这两个虚拟函数:

function myFunction() {
            for (var iter = 0; iter < 500000000; iter++) {
            if (iter==499999999) {alert ("done !");}
            }
}

function myFunction2() {
            alert ("Hi there !");
            }

Call them in this order, then change their order. 以此顺序呼叫他们,然后更改其顺序。 The second will always be executed once the first is complete. 一旦第一个完成,第二个将始终执行。

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

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