Javascript异步执行队列和setTimeout?

发布于 2024-10-06 05:53:50 字数 336 浏览 6 评论 0原文

我有一个脚本需要从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甜妞爱困 2024-10-13 05:53:50

setTimeout 是中断执行流程的典型方法。 Alert() 不是同一件事,它是同步的 - 它将停止您的代码,直到按下“确定”,然后从停止的地方恢复。当您使用 setTimeout 时,会释放线程来执行另一段代码。

唯一的弱点是不知道你在做什么。编码异步比编码同步稍微棘手一些。而且你必须注意你的上下文,因为使用“this”是行不通的:

object = {
    firstMethod: function(){
        setTimeout(function(){
            this.secondMethod(); // won't work!
        }, 30);
    },
    secondMethod: function(){}
}

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:

object = {
    firstMethod: function(){
        setTimeout(function(){
            this.secondMethod(); // won't work!
        }, 30);
    },
    secondMethod: function(){}
}
别在捏我脸啦 2024-10-13 05:53:50

setTimeout 就是这样做的方法。请注意,第二个参数是以毫秒为单位的超时而不是秒

setTimeout is the way to do it. Just note that the second parameter is timeout in miliseconds not seconds

一梦浮鱼 2024-10-13 05:53:50

基本上,您正在谈论从当前堆栈执行,换句话说,异步执行。 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 after setTimeout() will be executed before the callback function.

1ms in setTimeout() never works, however in terms of actually being 1ms. The fastest you can usually get is around 10ms in my experience.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文