Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!