javascript,等待某事真实然后运行动作 [英] javascript, wait for something to be true then run action
问题描述
好的标题有点说我需要的东西。因为在Javascript超时异步中我需要知道什么时候变成了现实。我不想要busyloop。
Well the title kindof says what I need. Because in Javascript timeouts asynchronous I need to know when something becomes true. I don't want busyloop.
想出:
function do_when(predicate, action, timeout_step) {
if (predicate()) {
action();
} else {
setTimeout(do_when, timeout_step, predicate, action, timeout_step);
}
}
这是好的Javascript还是我可以做得更好?
Is it good Javascript or can I make better?
推荐答案
它足够好,如果它很容易阅读并且它工作得很好那么它通常是很好的javascript。
It's decent enough, if it's easy enough to read and it works just fine then it's generally good javascript.
从性能的角度来说,无论何时设置为true都调用该函数通常会更好。因此,无论执行什么函数使谓词()
返回true,你最后都可以调用 action()
。但是我确定你能做到的就是这样,对吗?
Performance-wise, it's generally better to call the function whenever whatever is set to true happens. So in whatever function that executes to make predicate()
return true, you could just call action()
at the end. But I'm sure that's what you would have done if you could, right?
你也可以看一下使用回调,你可以在其中注册一个javascript函数变量或函数参数,当函数运行时,它执行为回调变量设置的任何函数。
You could also look at using a callback, where you register a javascript function to a particular variable or function argument and when the function is run it executes whatever function was set to the callback variable.
这篇关于javascript,等待某事真实然后运行动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!