jQuery asynchronous function call, no AJAX request

前端 未结 3 1597
耶瑟儿~
耶瑟儿~ 2020-12-02 13:18

This seems silly, but I can\'t find how to do an asynchronous function call with jQuery that doesn\'t involve some server-side request. I have a slow function that iterates

相关标签:
3条回答
  • 2020-12-02 13:44

    I was going to suggest looking at a timeout but alas. This post by John Resig (of jQuery) explains a bit about how JavaScript handles its single thread. http://ejohn.org/blog/how-javascript-timers-work/

    This article also explains: "One thing to remember when executing functions asynchronously in JavaScript, is all other JavaScript execution in the page halts until a function call is completed. This is how all the current browsers execute JavaScript, and can cause real performance issues if you are trying to call too many things asynchronously at the same time. A long running function will actually "lock up" the browser for the user. The same is true for synchronous function calls too."

    All that said, it's possible you could simulate an asynchronous function call yourself by breaking whatever loop you are doing into a smaller chunk and using setTimeout().

    For instance this function:

    // Sync
    (function() {
      for(var x = 0; x < 100000; ++x) {console.log(x)}
    })()
    
    // ASync
    var x = 0;
    setTimeout(function() {
       console.log(x++);
       if(x < 100000) setTimeout(arguments.callee, 1);
    } ,1)
    
    0 讨论(0)
  • 2020-12-02 13:51

    You might want web workers!

    Edit: I'm surprised how many people jumped to "its not possible" so I will elaborate. Web Workers are part of the HTML 5 spec. They allow you to spawn threads to run scripts in the background without blocking the UI. They must be external js files, are invoked by

    var worker = new Worker('my_task.js');
    

    and are communicated to via events.

    0 讨论(0)
  • 2020-12-02 13:59

    Javascript runs in a single thread and therefore if you have a slow function it will block everything else.

    UPDATE

    That will do some of what you want, but keep in mind that they are not widely supported supported in IE (I think they will be in IE10).

    Some resources on Web Workers:

    • Using Web workers
    • Wikipedia article on Web Workers
    • WHATWG: Web Workers

    Here are a few resources on accomplishing multi-threading without web workers. It's important to note that this isn't "true" multi-threading:

    • Multi-threading in Javascript (title is a little misleading; it's not true multi-threading)
    • Why doesn't Javascript support multi-threading?
    • Is there some way to do multi-threading in Javascript?
    • Simulating multi-threading using IFRAMEs (I'm not sure how viable this method is; it might be more trouble than it's worth and the law of diminishing returns probably applies.)
    0 讨论(0)
提交回复
热议问题