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

169
Vistas
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 Respuestas
Responde la pregunta

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 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