Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
How to properly add setInterval/setTimeout to my function

Pls, help!

The function should print the letters "A" through "F" to the console, one letter per second.

The function works without setInterval/setTimeout.

// setInterval(alphabet, 1000, 'a', 'f');

function alphabet(from, to) {
  var a = [], i = from.charCodeAt(0), j = to.charCodeAt(0);
  for (; i <= j; ++i) {
    setInterval(() => {
      a.push(String.fromCharCode(i));
    }, 1000);
  }
  // return console.log(a);
  return a;
}

console.log(alphabet('a', 'f'));
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

function printLetters(start, finish) {  
  //should add checks here to validate start comes before finish 

  console.log(start)
  if (start == finish) {
    return
  }
  else {
   setTimeout(printLetters, 1000, String.fromCharCode(start.charCodeAt(0)+1), finish)
  }
}

printLetters('a', 'f')

about 4 years ago · Juan Pablo Isaza Denunciar

0

You might wanna try this. You can paste it on codepen

var a = [];
function alphabet(from, to) {
    console.log(a);
    setInterval(() => {
        var i = from.charCodeAt(0);
        var j = to.charCodeAt(0);
        for (; i <= j; ++i) {
          if(a.includes(String.fromCharCode(i))){
             
          }else{
            console.log(String.fromCharCode(i))
            a.push(String.fromCharCode(i));
            break;
          }
        }
    }, 1000);
  return a;
}

alphabet('a', 'f');
about 4 years ago · Juan Pablo Isaza Denunciar

0

Here is a solution using an async sleep function.

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
async function alphabet(from,to){
  var currentLetter = from[0];
  while(currentLetter.charCodeAt(currentLetter[0]) != to.charCodeAt(to[0])+1){
    let l = currentLetter
    await sleep(1000)
    console.log(l)
    nextLetter = String.fromCharCode(currentLetter.charCodeAt(currentLetter[0])+1)
    currentLetter = nextLetter;
  }
}
alphabet('A','F');

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda