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

195
Vistas
SetInterval inside nested functions in JS is not working

I'm new to JS and trying to implement the setInterval inside the functions in Js.

JS:

var tar = document.getElementById("sample");
function dataSample(tar) {
    
   //setInterval variable

   var sInt = [];

   function setIntv(tar) {
     sInt[tar] = setInterval(function() {
        var currentDate = Date.now();
        var value = String(currentDate).substr(8, 2)
   }, 1000);
   console.log(sInt[tar]);
  }
 setIntv(tar);
}
dataSample(tar);

I need the 2 digit values to be updated every 1s using setInterval. But, It didnt work.

Console.log displays 1000. The setInterval Id(sInt[]) should display the values periodically, so that console.log(sInt[]); should display the updated values every 1s.

How to make setInterval work inside the function ?

Could someone please help?

Many thanks.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

console.log() shows you instance of interval, which, in your case, is identified with number 1000. If you want print values, you need to put console.log(value) inside interval function

instead of this:

function setIntv(tar) {
     sInt[tar] = setInterval(function() {
        var currentDate = Date.now();
        var value = String(currentDate).substr(8, 2)
   }, 1000);
   console.log(sInt[tar]);
}

write this:

function setIntv(tar) {
     sInt[tar] = setInterval(function() {
        var currentDate = Date.now();
        var value = String(currentDate).substr(8, 2);
        console.log(value);
   }, 1000);
}

or if you need to acces this value outside of interval function (despite your comment):

function setIntv(tar) {
     setInterval(function() {
        var currentDate = Date.now();
        var value = String(currentDate).substr(8, 2);
        sInt[tar] = value;
   }, 1000);
}

console.log(sInt[tar]);
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