简体   繁体   中英

How to abort JavaScript async functions?

For example, you have a Web Music Player app. When a user clicks on the play button, a function fires, looking for the MP3 data, setting up the player etc. etc., but then the user changes his mind and clicks play on another track. Is there a way to just cancel the previous function completely? I know you can abort XHRequests, but I mean like whole functions. Maybe JS Promises?

In javascript a synchronous function will run to completion. It will not be interrupted by another user action. So, in your scenario if a function fires and is setting up the player, that function will run to completion before the next user event is processed. So, you can't abort a synchronous function in javascript and there would be no way to anyway because (except for web workers which isn't what we're discussing here), javascript is single thread so as long as function is running, it will run to completion and no other user events will be processed.

If, however, that function has some sort of asynchronous operation in it (such as loading something via ajax or a player loading a music file), then whether or not that async operation can be aborted depends entirely upon the specific support in that operation - there is no generic abort. For us to help you with asynchronous details, you would need to disclose your actual code so we can see what you're doing.

Promises are not a tool for aborting asynchronous operations. In fact, they are a tool for somewhat the opposite as they report on what and when things happened to asynchronous operations. They don't cause those things to happen, then just notify observers when things happened to asynchronous operations.


As is generally the case with StackOverflow questions, we can help much more in-depth if you disclose your actual code because that would change your question from a theoretical discussion to a practical analysis of what the options are for your actual code.

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