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

124
Vistas
Javascript setInterval not working for object method

I'm trying to run a 'Car' object method across the browser window with 'setInterval' but it only work once. What's the problem of my code? Also, I am confused if we put the function in setInterval with parenthesis or without it?

Here is my code:

var Car = function(x, y) {
  this.x = x;
  this.y = y;
  //   drawing in constructor
  this.draw();
};
Car.prototype.draw = function() {
  var carhtml =
    '<img src="https://www.pngitem.com/pimgs/m/195-1953962_vector-vintage-classic-car-free-hd-image-clipart.png">';

  this.carElement = $(carhtml);
  this.carElement.css({
    position: "absolute",
    left: this.x,
    top: this.y,
    width: 400,
  });
  $("body").append(this.carElement);
};
Car.prototype.moveRight = function() {
  this.x += 10;
  this.carElement.css({
    left: this.x,
    top: this.y,
  });
};
var classicCar = new Car(0, 100);
setInterval(classicCar.moveRight, 1000);
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are losing the reference to the this variable. Bind it to the object

setInterval(classicCar.moveRight.bind(classicCar), 1000);

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