-1

Trying to make a react native app that takes text as input and converts it to morse code, using the phone's torch. I can get the translated morse code but when I try to convert that to light using the torch, the loop only runs once (There is a short flash) and then exits. Why is that happening/how do I fix that?

var j;
for(j = 0; j < cipher.length; j++) {
    if(cipher[j] == '.') {
        Torch.switchState(true);
        setTimeout(function(){Torch.switchState(false)},200);
        setTimeout(function(){},200);
    }
    else if(cipher[j] == '-') {
        Torch.switchState(true);
        setTimeout(function(){Torch.switchState(false)},600);
        setTimeout(function(){},200);
    }
    else if(cipher[j] == ' ') {
        setTimeout(function(){},600);
    }
    else {
        setTimeout(function(){},1400);
    }
}

1 Answers1

1

The setTimeout() function needs a callback function to work. I guess that if you put the "if" conditionals into the callback functions it will work. I'll leave a example down here:

HTML:

<p>Live Example</p>
<button onclick="delayedAlert();">Show an alert box after two seconds</button>
<p></p>
<button onclick="clearAlert();">Cancel alert before it happens</button>

Javascript:

var timeoutID;

function delayedAlert() {
  timeoutID = window.setTimeout(window.alert, 2*1000, 'That was really slow!');
}

function clearAlert() {
  window.clearTimeout(timeoutID);
}

Another possibility is to use an anonymous function to call your callback, but this solution is a bit more expensive. Example:

var intervalID = setTimeout(function() { myFunc('one', 'two', 'three'); }, 1000);

Checkout the Official Guides in: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

Timothy Dalton
  • 1,290
  • 2
  • 17
  • 24