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

167
Views
jQuery/Javascript print the value from return function

How to return value from function to html element.

Below is the sample code:

$.fn.countdown = function(toTime){
  var x = setInterval(function(){
    var now = new Date().getTime();
    var distance = toTime - now;

    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    var value = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
    console.log(value);
    return value;
  }, 1000);
};

$('#my_div').countdown(new Date("Jan 5, 2024 15:37:25").getTime());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I need the result value from that function print to #my_div.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The issue is because your return statement is inside the setInterval() handler and is therefore not returned from the $.fn.countdown invocation.

You instead need to reference the element which your jQuery extension library was instantiated on, using the this keyword, and then update that element. In the example below I used the text() method.

$.fn.countdown = function(toTime) {
  let $el = $(this);
  
  let timeUpdate = () => {
    var now = new Date().getTime();
    var distance = toTime - now;

    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    var value = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
    $el.text(value);
  }
  
  timeUpdate(); // run on instantiation
  var intervalId = setInterval(timeUpdate, 1000); // run every second
};

$('#my_div').countdown(new Date("Jan 5, 2024 15:37:25").getTime());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_div"></div>

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!