Javascript异步执行队列和setTimeout?
我有一个脚本需要从 JavaScript 执行队列中删除。我发现我可以通过几种方法来做到这一点。
alert();//of course we can't use this one.
setTimeout(function(){
someScript();//works, but are there vulnerabilites?
}, 1);
还有哪些其他方法以及跳出 JavaScript 执行队列的正确方法是什么?
如果setTimeout是最好的选择,那么使用setTimeout有哪些漏洞?未来是否可能出现问题,超时代码不会被调用的可能性,速度问题等。
I have a script that I need to bump out of the javascript execution queue. I have found that I can do this with a couple methods.
alert();//of course we can't use this one.
setTimeout(function(){
someScript();//works, but are there vulnerabilites?
}, 1);
What other methods are there and what is the correct way to bump out of the javascript execution queue?
If setTimeout is the best option, what are the vulnerabilities of using setTimeout? Are there possible future problems, possibility that the code in the timeout won't get called, speed issues, etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
setTimeout 是中断执行流程的典型方法。 Alert() 不是同一件事,它是同步的 - 它将停止您的代码,直到按下“确定”,然后从停止的地方恢复。当您使用 setTimeout 时,会释放线程来执行另一段代码。
唯一的弱点是不知道你在做什么。编码异步比编码同步稍微棘手一些。而且你必须注意你的上下文,因为使用“this”是行不通的:
setTimeout is the typical way of interrupting the execution flow. alert() is not the same thing, it is synchronous - it will stop your code until OK is pressed, and resume where it left off. When you use setTimeout, that frees up the thread to go execute another section of code.
The only vulnerabilities are not knowing what you are doing. Coding async is a little trickier than coding sync. And you have to watch your context, because using "this" won't work:
setTimeout 就是这样做的方法。请注意,第二个参数是以毫秒为单位的超时而不是秒
setTimeout is the way to do it. Just note that the second parameter is timeout in miliseconds not seconds
基本上,您正在谈论从当前堆栈执行,换句话说,异步执行。
setTimeout()
是这种情况下的方法,setTimeout()
之后的代码将在回调函数之前执行。setTimeout()
中的1ms
永远不会起作用,但实际上是1ms
。根据我的经验,通常最快的速度约为10ms
。Basically you are talking about executing out of current stack, in other words asynchronously.
setTimeout()
is the way to go in this case and the code aftersetTimeout()
will be executed before the callback function.1ms
insetTimeout()
never works, however in terms of actually being1ms
. The fastest you can usually get is around10ms
in my experience.