function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } var sel = document.querySelector("select"); sel.addEventListener("change", function() { var val = sel.selectedOptions[0].id.split('-') sel.selectedOptions[0].value = getRandomInt(+val[0], +val[1]) setInterval(function() { sel.selectedOptions[0].value = getRandomInt(+val[0], +val[1]) }, 5000); console.log(sel.value); }) 
 <select id="periodicity"> <option id="1-60" value="">Одуванчик </option> <option id="25-70" value="">Чабрец </option> <option id="1-100" value="">Полынь </option> </select> 

Help with setInterval need to update the value every 5 seconds

  • what does not work? - Igor
  • And if console.log() inserted into setInterval() ?)) - entithat
  • The code above works. - Grundy
  • Please note that for each change event, an additional timer will be triggered. - Igor
  • Comment not relevant to the question: Your getRandomInt function getRandomInt never return the max value. - Dmytryk

1 answer 1

 function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } var sel = document.querySelector("select"); //---------------------------------------------------------------- var options = sel.options; // //---------------------------------------------------------------- setInterval(function() { //---------------------------------------------------------------- // Каждые 5 сек меняет value ... Object.values(options).forEach(function(el) { var val = el.id.split('-'); el.value = getRandomInt(+val[0], +val[1]) console.log(el.value); }) }, 5000); //---------------------------------------------------------------- sel.addEventListener("change", function() { /// Возможно эта часть вам уже не нужна... var val = sel.selectedOptions[0].id.split('-') sel.selectedOptions[0].value = getRandomInt(+val[0], +val[1]) console.log(sel.value); }) 
 <select id="periodicity"> <option id="1-60" value="">Одуванчик </option> <option id="25-70" value="">Чабрец </option> <option id="1-100" value="">Полынь </option> </select> 

  • Is it possible to make only 1 value of the selected field change? - Nikolay
  • @ Nikolay You have one "changed" field. - Kosta B.