setTimeout()
只是安排将来运行的东西,其余的Javascript继续运行。它不会阻止进一步的Javascript执行。这通常被称为“异步”操作。它在后台运行,并在将来完成其工作时的某个时间调用回调。它也被称为“非阻塞”,因为它不会阻塞你的其他Javascript执行。你想不运行,直到setTimeout()
大火,必须把setTimeout()
回调内部或从那里叫
什么。
// define function
function timer(){
myVar = setTimeout(function() {
console.log("SLOW");
}, 10000);
}
// schedule first timer
setTimeout(function() {
$("#nytLevel").hide();
// now start second timer
timer();
}, 3000);
值得一提的是,jQuery有一个.delay()
方法与动画等功能放入队列中工作,而且有时可以简化你的代码。在上述情况下,你可以这样做:
$("#nytLevel").delay(3000).hide().delay(10000).queue(function(next) {
console.log("SLOW");
next(); // keep the queue moving in case there's something else in the queue
});
请注意:.delay(xxx)
只与自己使用队列(如动画),或你把自己使用.queue()
队列方法jQuery方法的工作(如我已经在上面显示)。
你是如何执行你的代码?订单是什么?提供的代码根本不能解释它...... – Rayon
这听起来很像[XY问题](http://xyproblem.info)。为什么不能在第一次超时时间内使用timer()调用? – JJJ
@pushalu setTimeout是一个异步函数 –