[英]javascript anonymous setTimeout function
is it possible in jScript to do something like the following using multiple anonymous setTimeout functions? 在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');
// finally, wait for eventCounter to be equal to 3
console.log('eventCounter is now equal to three');
I had hoped something like this might have worked: 我希望这样的事情可能会起作用:
setTimeout( () => { // fake code
if ( eventCounter <= 1234 ) {
this(); // fake code, this() is not a function
} else {
console.log('eventCounter is now over 1234');
}
}, 200);
or maybe Promises is the way to go? 还是承诺是要走的路?
otherwise it seems like i end up with some sort of deeply embedded nested perform loop with multiple function names, which i had hoped to avoid. 否则,看来我最终会遇到某种深层嵌套的具有多个函数名的嵌套执行循环,我希望避免这种情况。
thank you very much. 非常感谢你。
I found this on SO, but unfortunately i am unable to remember where i found it: 我在SO上找到了它,但是不幸的是我不记得我在哪里找到它:
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;
and another perhaps better excellent idea was suggested here : 这里提出了另一个也许更好的好主意:
(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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.