0

My code is bellow, it doesn't throw errors but it stops after running ones.

I tried reviewing this codes and searching through documentation, but couldn't find anything, possibly due to my level of knowledge.

var timeNumbers = ['count','working','resting'];
var amountData  = {'count':0,'working':0,'resting':0};   

function fromCount(){
    if(timeVa['working'] == false) return;
    var amountDataNo1 = Array.from(amountData);
    var dataW = setInterval(loseTimeW(1),1000);

    function loseTimeW(n){
        if(amountDataNo1[timeNumbers[n]] == 0){
            clearInterval(dataW);
            timeVa['resting'] == true;
        }else{
            amountDataNo1[timeNumbers[n]]--;
        }
    }
}
n1kkou
  • 3,096
  • 2
  • 21
  • 32
kentaa
  • 19
  • 3
  • 1
    You should provide a [mcve], not all of your code. – Quentin Jan 10 '19 at 11:19
  • 2
    Duplicate: https://stackoverflow.com/questions/11837562/javascript-settimeout-wont-wait-to-execute – Quentin Jan 10 '19 at 11:20
  • 2
    Another duplicate: https://stackoverflow.com/questions/10182714/why-does-the-setinterval-callback-execute-only-once – Quentin Jan 10 '19 at 11:20
  • The first argument of `setInterval()` is the function it must invoke periodically. You don't pass a function to it but `undefined`. – axiac Jan 10 '19 at 11:29

1 Answers1

2

The first argument of setInterval() is the function it must invoke periodically.

The first argument you pass to setInterval() is the value returned by the call loseTimeW(1). But the loseTimeW() function does not return anything, consequently the value of loseTimeW(1) is undefined.

I guess your intention is to invoke loseTimeW() with argument 1 every 1000 milliseconds. You can achieve this easily. setInterval() accepts two or more arguments. It passes the arguments starting with the third one (if any) to the callback (argument #1) when it invokes it.

The working code is something like:

var dataW = setInterval(loseTimeW, 1000, 1);

Read more about setInterval().

axiac
  • 68,258
  • 9
  • 99
  • 134
  • Alternatively, `setInterval(new Function() { loseTimeW(1); }, 1000);` , or `setInterval(() => loseTimeW(1), 1000);` – Ben R. Jan 10 '19 at 11:36
  • @BenR. [`new Function()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function#Syntax) does not work this way. – axiac Jan 10 '19 at 11:39