2010-02-14 85 views

回答

5

查看Rhino Examples頁面上的Multithreaded Script Execution示例。基本上,JavaScript不直接支持線程,但您可以使用Java線程來實現您正在尋找的內容。

36

您可以使用java.util.Timerjava.util.TimerTask推出自己的設置/清除超時,並設置/清除間隔功能:

var setTimeout, 
    clearTimeout, 
    setInterval, 
    clearInterval; 

(function() { 
    var timer = new java.util.Timer(); 
    var counter = 1; 
    var ids = {}; 

    setTimeout = function (fn,delay) { 
     var id = counter++; 
     ids[id] = new JavaAdapter(java.util.TimerTask,{run: fn}); 
     timer.schedule(ids[id],delay); 
     return id; 
    } 

    clearTimeout = function (id) { 
     ids[id].cancel(); 
     timer.purge(); 
     delete ids[id]; 
    } 

    setInterval = function (fn,delay) { 
     var id = counter++; 
     ids[id] = new JavaAdapter(java.util.TimerTask,{run: fn}); 
     timer.schedule(ids[id],delay,delay); 
     return id; 
    } 

    clearInterval = clearTimeout; 

})() 
+0

Whit您的代碼片段,我能夠運行茉莉花無需使用EnvJS即可在Rhino中進行測試。謝謝! – 2011-05-28 15:25:01

+0

我希望我能給你100個upvotes,非常棒。非常感謝。 – Upgradingdave 2011-08-12 17:03:46

+2

太棒了。謝謝!爲了與瀏覽器完全兼容,您還需要處理延遲的遺漏。 MDN表示,根據HTML5規範的最小延遲是4ms,所以添加以下內容:if(delay == null){delay = 4; } – 2012-04-20 10:08:56

2

使用ScheduledThreadPoolExecutor,犀牛1.7R4兼容,並提出了另一個版本的@Nikita-Beloglazov

var setTimeout, clearTimeout, setInterval, clearInterval; 

(function() { 
    var executor = new java.util.concurrent.Executors.newScheduledThreadPool(1); 
    var counter = 1; 
    var ids = {}; 

    setTimeout = function (fn,delay) { 
     var id = counter++; 
     var runnable = new JavaAdapter(java.lang.Runnable, {run: fn}); 
     ids[id] = executor.schedule(runnable, delay, 
      java.util.concurrent.TimeUnit.MILLISECONDS); 
     return id; 
    } 

    clearTimeout = function (id) { 
     ids[id].cancel(false); 
     executor.purge(); 
     delete ids[id]; 
    } 

    setInterval = function (fn,delay) { 
     var id = counter++; 
     var runnable = new JavaAdapter(java.lang.Runnable, {run: fn}); 
     ids[id] = executor.scheduleAtFixedRate(runnable, delay, delay, 
      java.util.concurrent.TimeUnit.MILLISECONDS); 
     return id; 
    } 

    clearInterval = clearTimeout; 

})() 

參考:https://gist.github.com/nbeloglazov/9633318

相關問題