1

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.

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

4 Comments

This working good. (y)
Glad to help. Note that I just updated the answer to remove the initial delay before the countdown is displayed in the DOM.
Yes, it;s good. Also 1 question, how to stop the countdown if distance < 0 ? I tried clearInterval(intervalId); but it still run the countdown
That should work, so long as the code was put in the right place - try putting it after this line after var distance = toTime - now;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.