Help please, I can not figure out the cycle in JS. Now I use this crutch:

if (video == 199) { if (length < 30) { document.getElementById('price').innerHTML = ('$50'); } else if (length < 60) { document.getElementById('price').innerHTML = ('$75'); } else if (length < 90) { document.getElementById('price').innerHTML = ('$100'); } else { document.getElementById('price').innerHTML = ('$125'); } } 

But I need to change the length in increments of 30 - price increased by 25

  • Increase you need not a number but a number. Use let i = 0; for (; i <1000; i ++) {if (length <i * 30) document.getElementById ('price'). innerHTML = ('$' + (25 + i * 25)); } - test123
  • one
    document.getElementById ('price'). innerHTML = ('$' + Number (50 + Math.trunc (length / 30) * 25)); - uber42
  • Yes, I was stupid, I immediately didn’t need a cycle ... - test123

3 answers 3

Well, if every 30 seconds, then you need setInterval

 const price = document.getElementById('price'); let priceValue = 0; setInterval(() => { price.innerHTML = `$${priceValue}`; priceValue += 25; }, 300); // в миллисекундах, вам нужно поставить 30000 
 <div id='price'></div> 

  • @ H4nteR, didn’t quite understand what it is for - ThisMan
  • I am sorry, I am nervous, I did not correctly describe the problem. Seconds I set the input type = "number", it is necessary that the price increased by 30 zeros in price by 25 - H4nteR
  • @ H4nteR, I still did not understand anything, but in any case, you need to use setInterval , the second parameter is the number of milliseconds through which the function - ThisMan will be called
  • there are just two numbers, changing the first 30, 60, 90, etc., the other should be changed - 25, 50, 75, etc. Now it seems to write more clearly ( - H4nteR
  • one
    @ H4nteR then update the question and provide the expected behavior - ThisMan 2:32 pm

You can use the ternary operator. The code is more compact, but the essence is the same.

 var text = document.getElementById('price').innerHTML; if (video == 199) { length < 30 ? text = '$50' : (length < 60 ? text = '$75' : (length < 90 ? text = '$100' : text = '$125')); } 

    Thank you, of course, I didn’t immediately ask a very correct question, I was in a hurry.

    They told me this solution:

     var length = 0; $('#seconds').each(function() { length += parseInt($(this).val()); }); var step = 0; step = ((length / 30) * 25); document.getElementById('price').innerHTML = ('$' + step); 
     <input type="number" step="30" value="30" id="seconds"> <div id="price"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>