Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda