简体   繁体   中英

Javascript asynchronous execution queue and 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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM