我有下面的功能,这是调用按钮单击,然后调用另一个函数内的定时器。为什么在最后调用回调函数以及如何测试函数?
下面是代码:
<button id="starter">Start</button>
JS:
document.getElementById ("starter").addEventListener ("click", myFunction, false);
function myFunction() {
var start = new Date().getTime();
console.log("Start", start);
d3.timer(() => {
var timepassed = new Date().getTime() - start;
console.log("Time elapsed", timepassed);
helloBlah(timepassed);
if(timepassed >= 200) return true;
});
console.log(" Why am I triggered first rather than the timer?");
}
function helloBlah(e){
console.log("Hello Blah");
}
这里是JSFiddle。
为什么d3计时器和里面的函数晚于它下面的控制台消息被调用?我如何在控制台消息之前调用它,以及如何在Jasmine中为这些类型的函数编写测试?
定时器是异步和JavaScript是单线程的。这意味着回调将不会被调用,直到时间到,并且当前正在运行的线程完成。 – 4castle