Execute Background Task In Javascript

后端 未结 9 1630
迷失自我
迷失自我 2020-11-28 22:39

I have a cpu intensive task that I need to run on the client. Ideally, I\'d like to be able to invoke the function and trigger progress events using jquery so I can update

9条回答
  •  盖世英雄少女心
    2020-11-28 23:37

    This is a very basic example of how to create threads in JavaScript. Note that is is up to you to interrupt your thread functions (yeld instruction). If you want, you can use a setTimeout instead of my while loop to run the scheduler periodically. Note also that this example only works with JavaScript version 1.7+ (firefox 3+) you can try it here: http://jslibs.googlecode.com/svn/trunk/jseval.html

    //// thread definition
    function Thread( name ) {
    
        for ( var i = 0; i < 5; i++ ) {
    
            Print(i+' ('+name+')');
            yield;
        }
    }
    
    //// thread management
    var threads = [];
    
    // thread creation
    threads.push( new Thread('foo') );
    threads.push( new Thread('bar') );
    
    // scheduler
    while (threads.length) {
    
        var thread = threads.shift();
        try {
            thread.next();
            threads.push(thread);
        } catch(ex if ex instanceof StopIteration) { }
    }
    

    The output is:

    0 (foo) 0 (bar) 1 (foo) 1 (bar) 2 (foo) 2 (bar) 3 (foo) 3 (bar) 4 (foo) 4 (bar) 
    

提交回复
热议问题