javascript匿名设置超时函数
在jScript中,是否可以使用多个匿名setTimeout函数执行以下操作javascript匿名设置超时函数,javascript,Javascript,在jScript中,是否可以使用多个匿名setTimeout函数执行以下操作 var eventCounter; // wait for eventCounter to be equal to 1 console.log('eventCounter is now equal to one'); // pause for eventCounter to be equal to 2 console.log('eventCounter is now equal to two'); // fina
var eventCounter;
// wait for eventCounter to be equal to 1
console.log('eventCounter is now equal to one');
// pause for eventCounter to be equal to 2
console.log('eventCounter is now equal to two');
// finally, wait for eventCounter to be equal to 3
console.log('eventCounter is now equal to three');
我曾希望这样的事情能够奏效:
setTimeout( () => { // fake code
if ( eventCounter <= 1234 ) {
this(); // fake code, this() is not a function
} else {
console.log('eventCounter is now over 1234');
}
}, 200);
setTimeout(()=>{//false code
如果(eventCounter我发现它是开着的,但不幸的是我记不起在哪里找到的:
var waitValue = false;
var counter = 0;
(function tester() {
if ( waitValue ) {
console.log('finally true');
} else {
if ( counter > 1000 ) {
console.log('waited too long');
process.exit;
} else {
console.log('still waiting, counter = ' + counter++);
setTimeout(tester, 1000);
}
}
})();
// wait a few seconds and enter this into the console:
var waitValue = false;
另一个也许更好的好主意是:
(功能循环(计数器){
如果(等待值){
log('waitValue现在为true');
决议(“第一承诺”);
}else if(counter)您可能希望查看promises和async
/wait
语法。后者是标准化的,但尚未在大多数JavaScript引擎(node.js、浏览器等)中实现,但您可以通过Babel(以及其他)运行代码将async
/wait
转换为浏览器支持的代码。您是否只是想每秒都有一个勾号?什么是eventCounter
?谁增加它?如果您想要递归轮询循环,只需使用一个可以调用的命名函数。“eventCounter”这是我刚刚编出来的,服务器进程将控制这个值。看来,如果不使用函数,或是将我疲惫的旧大脑包裹在承诺上,就无法做到这些。
(function loop(counter) {
if ( waitValue ) {
console.log('waitValue is now true');
resolve('FIRST PROMISE');
} else if ( counter <= 0 ) { // dont wait forever.
reject('waited too long');
} else {
console.log('Count down: ' + counter);
setTimeout( loop.bind(null, counter-1), 3000);
}
})(counter); // initial value of count-down