Home > Net >  How to pass element to anonymus function in jquery?
How to pass element to anonymus function in jquery?

Time:05-24

I'm creating a countdown element and I want to pass each element to setinterval function to update it each second

                var countDownDate = new Date($(this).data('date')).getTime();

                setInterval(function() {
                    var now = new Date().getTime();

                    var distance = countDownDate - now;

                    // Time calculations for days, hours, minutes and seconds
                    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);

                    $(this).find('.days').text(days);
                    $(this).find('.hours').text(hours);
                    $(this).find('.minutes').text(minutes);
                    $(this).find('.seconds').text(seconds);
                }, 1000);
            });

thanks in advance

CodePudding user response:

Your questions don't describe what you really wanted, but there are a few ways to access these elements inside the function.

  1. Using an arrow function
 setInterval(() => {
   /*
   your code goes here without changes
   */
 }, 1000)
  1. Passing parameters
 setInterval(function(days, hours, minutes, seconds) {
   /*
   your code goes here without changes
   */
   days.text(days);
   hours.text(hours);
   minutes.text(minutes);
   seconds.text(seconds);
 }, 1000, $(this).find('.days'), $(this).find('.hours'), $(this).find('.minutes'), $(this).find('.seconds'))
  1. Binding
setInterval((function() {
  /*
  your code goes here without changes
  */
}).bind(this), 1000)

You could just also pass this as an argument. I would use the arrow function since it's a more modern approach.

  • Related