Javascript异步执行队列和setTimeout? [英] Javascript asynchronous execution queue and setTimeout?

查看:105
本文介绍了Javascript异步执行队列和setTimeout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本需要从javascript执行队列中删除.我发现我可以使用几种方法来做到这一点.

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);

还有什么其他方法,什么是摆脱javascript执行队列的正确方法?

What other methods are there and what is the correct way to bump out of the javascript execution queue?

如果setTimeout是最佳选择,那么使用setTimeout的漏洞有哪些?将来是否可能出现问题,是否可能无法调用超时代码,速度问题等?

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.

推荐答案

setTimeout是中断执行流的典型方法. alert()不是同一件事,它是同步的-它会停止您的代码,直到按下OK为止,然后从停止的地方继续.当您使用setTimeout时,这将释放线程以执行另一部分代码.

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.

仅有的漏洞不知道您在做什么.编码异步比编码同步要难一些.而且您必须注意上下文,因为使用"this"将不起作用:

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(){}
}

这篇关于Javascript异步执行队列和setTimeout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆