2016-12-20 6 views
0

これも可能ですか?同じ機能を別々の時間間隔で使用したい。どのようにして関数を5000で実行させ、関数内のコードの特定の部分を実行することができますか?だから、呼び出しでパラメータを渡す同じ関数を異なる間隔で呼び出したときにコードの異なる部分を実行する方法

var moto = function(){ 
    // at 5000 run this part of code 
    console.log("did stuff when called at 5000 time interval") 

    // at 6000 run this part of code 
    console.log("did stuff when called at 6000 time interval") 
} 

window.setInterval(moto, 5000) 
window.setInterval(moto, 6000) 

答えて

5

:ここ

のアイデアを与えるための一例です。

var moto = function(val){ 
    if(val===5000) { 
    // at 5000 run this part of code 
    console.log("did stuff when called at 5000 time interval"); 
    } else { 
    // at 6000 run this part of code 
    console.log("did stuff when called at 6000 time interval"); 
    } 
} 

window.setInterval(moto.bind(this, 5000), 5000); 
window.setInterval(moto.bind(this, 6000), 6000); 
0

一つの方法は、のようなあなたの機能にいくつかのparamを渡すことになります。あなたは本当にそれは同じ機能になりたい場合は

var moto = function(runAt){ 
    // at 5000 run this part of code 
    if(runAt==500) 
    console.log("did stuff when called at 5000 time interval") 

    // at 6000 run this part of code 
    if(runAt==600) 
    console.log("did stuff when called at 6000 time interval") 
} 

window.setInterval(function() {moto(500)}, 5000) 
window.setInterval(function() {moto(600)}, 6000) 
+0

そして – epascarello

+0

@epascarelloは –

+0

それを修正そして今、それはちょうど私のようなものです一度それが実行されます... – epascarello

2

、希望の遅延の最大公約数の遅延時間を設定し、この場合はgcd(5000, 6000) = 1000です。そしてカウンターを使います。

var counter = 0; 
 
var moto = function() { 
 
    ++counter; 
 
    if (counter % 5 == 0) // at 5000 run this part of code 
 
    console.log("did stuff when called at 5000 time interval") 
 
    if (counter % 6 == 0) // at 6000 run this part of code 
 
    console.log("did stuff when called at 6000 time interval") 
 
}; 
 
window.setInterval(moto, 1000);

+0

遅延の最小公倍数に達すると、カウンタをリセットすることができます。 – Oriol

0

物事の別の方法を見て:P

class Moto { 
 
    constructor(delay) { 
 
    this.delay = delay 
 
    setInterval(this.fn.bind(this), delay) 
 
    } 
 
    
 
    fn() { 
 
    // at 5000 run this part of code 
 
    if (this.delay === 5000) 
 
     console.log("did stuff when called at 5000 time interval") 
 
    
 
    // at 6000 run this part of code 
 
    if (this.delay === 6000) 
 
     console.log("did stuff when called at 6000 time interval") 
 
    } 
 
} 
 
    
 
new Moto(5000) 
 
new Moto(6000)

関連する問題