2011-08-05 34 views
24

我想知道如何實現: 隨機數後產生一個隨機數。並重用它。Randomize setInterval(如何在隨機間隔後重寫相同的隨機數)

function doSomething(){ 
    // ... do something..... 
} 

var rand = 300; // initial rand time 

i = setinterval(function(){ 

    doSomething(); 
    rand = Math.round(Math.random()*(3000-500))+500; // generate new time (between 3sec and 500"s) 

}, rand); 

然後反覆做。

到目前爲止,我能夠生成一個隨機的時間間隔,但它一直持續到頁面刷新(生成的時間間隔不同)。

感謝

回答

68

這是一個很乾淨,清晰的方式來做到這一點:

http://jsfiddle.net/Akkuma/9GyyA/

function doSomething() {} 

(function loop() { 
    var rand = Math.round(Math.random() * (3000 - 500)) + 500; 
    setTimeout(function() { 
      doSomething(); 
      loop(); 
    }, rand); 
}()); 

編輯:

說明: 循環只存在於立即調用的函數上下文中,因此它可以遞歸調用自身。

+0

完美!我喜歡它。 – Timmerz

+1

不錯的解決方案,但是如果你想能夠在一段時間內刪除「間隔」,它需要一些改變。 –

+2

@toprightgamedev如果你想停止循環,只需用你需要的邏輯在setTimeout周圍放置一條if語句即可。 – Akkuma

4

像這樣的東西應該工作 - 用setTimeout()代替你可以每次設定一個新的隨機值:

function doSomething() { 
    alert("doing something"); 
} 

function init() { 
    var myFunction = function() { 
     doSomething(); 
     var rand = Math.round(Math.random() * (3000 - 500)) + 500; // generate new time (between 3sec and 500"s) 
     setTimeout(myFunction, rand); 
    } 
    myFunction(); 
} 

$(function() { 
    init(); 
}); 

Working jsFiddle here

+0

@roXon:是的 - 那樣你可以每次更新隨機間隔 – BrokenGlass

+0

這是最後的jQuery,不是純Javascript。 – felwithe

4

只需設置間隔您蘭特每次(和第一清除它)

function doSomething(){ 
    // ... do something..... 
} 

var i; 
var rand = 300; 

function randomize() { 
    doSomething(); 
    rand = Math.round(Math.random()*(3000-500))+500; 
    clearInterval(i); 
    i = setInterval('randomize();', rand); 
} 

i = setInterval('randomize();', rand); 

,或者嘗試使用的setTimeout(和randing後重新設置)

+1

在旁邊注意它應該'setInterval(randomize,rand);' –

1

只是扔我的帽子環

var keepLooping = true; 
    (function ontimeout(){ 
     if(keepLooping){ 
      doTheAction(); 
      setTimeout(ontimeout, Math.random() * 100); 
     } 
    })(); 

取決於如果你想要把doTheAction()setTimeout回調與否裏面。我認爲把它放在/之前是很好的。如果你想要最初的延遲,然後把它放在裏面,如果沒有,簡單地放在外面。