0

I have one problem with setInterval. When user select option(time) i would to time of setInterval change dynamic. This code works if user change from the first (select) and if he change from 10 to 1, not 1 to 10.
if i console.log(convertTime) i see dynamic change, but not in this setInterval..

Can I use your skills ? Thanks

Function inter() make random words

choiseTime.addEventListener("change", (e) => 
  {
  let timeSelect = e.target.selectedIndex;
  convertTime    = timeSelect * 1000;
  inter();
  setInterval(inter, convertTime);
  if (timeSelect < 4) 
    {
    alert.innerHTML = `En sélectionnant une durée de ${timeSelect}s vous irez sans doute trop vite. L'intervalle conseillé est de 4 à 7s par mot.`;
    } 
  else 
   {
   alert.innerHTML = "";
   }
 }); 
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
Bilal
  • 1
  • Welcome to SO. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask). To get the best answers to your question we like to see that you've attempted to solve the problem yourself first using a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Here's a [question checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) you might find useful... – Mister Jojo Jul 25 '22 at 14:06
  • _"This code works if user change from the first (select) and if he change from 10 to 1, not 1 to 10."_ - No. This script doesn't work like that. Every `change` starts a new interval and does not modify an existing one. – Andreas Jul 25 '22 at 14:08
  • `let` is missing on `convertTime = timeSelect * 1000;` – Mister Jojo Jul 25 '22 at 14:09

1 Answers1

0

var alert = document.querySelector('#alert')
var interval
var timeToWait = 1000

const startCycle = (toWait) => {
  if(interval){
    clearInterval(interval)
  }
  interval = setInterval(()=>{
    console.log('I\'ve waited '+toWait/1000+'s')
  }, toWait)
}

document.querySelector('#start').addEventListener("click", (e) => {
  startCycle(timeToWait)
});

document.querySelector('#plus').addEventListener("click", (e) => {
  timeToWait = timeToWait + 100
  startCycle(timeToWait)
  if(timeToWait >= 500){
    alert.innerHTML = `En sélectionnant une durée trop basse vous irez sans doute trop vite.`;
  }
});

document.querySelector('#minus').addEventListener("click", (e) => {
  if(timeToWait !== 100){
    timeToWait = timeToWait - 100
    startCycle(timeToWait)
  }
  if(timeToWait < 500){
    alert.innerHTML = `En sélectionnant une durée trop basse vous irez sans doute trop vite.`;
  }

});
<div style='display: flex;'>
 <button id='plus'>Augmenter</button>
 <button id='start'>Commencer</button>
 <button id='minus'>Diminuer</button>
<div>
<p id='alert'></p>
JeanJacquesGourdin
  • 1,496
  • 5
  • 25