SetInterval, как сделать чтобы смещение каждые 800мс были на разное расстояние, рассчитанное случайным образом

'use strict';
let Car = function(x, y) {
  this.x = x;
  this.y = y;

  this.spead = 40;

  this.draw();
};

Car.prototype.draw = function() {
  let carHtml = '<img src="http://nostarch.com/images/car.png">';

  this.carElement = $(carHtml);

  this.carElement.css({
    position: 'absolute',
    left: this.x,
    top: this.y
  });

  $('body').append(this.carElement);
};


Car.prototype.moveRight = function(distance) {
  this.x += distance;

  this.carElement.css({
    left: this.x,
    top: this.y
  });

};



let tesla = new Car(20, 20);
let nissan = new Car(300, 70);


let t = Math.floor(Math.random() * (200 - 0 + 1));
setInterval(tesla.moveRight.bind(tesla, t), 800);
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>


Ответы (2 шт):

Автор решения: YakovL

Вы сейчас вычисляете смещение лишь однажды, и потом запускаете setInterval с ним:

let t = Math.floor(Math.random() * (200 - 0 + 1));
setInterval(tesla.moveRight.bind(tesla, t), 800);

Очевидно, нужно вычислять каждый раз:

setInterval(() => {
    let t = Math.floor(Math.random() * (200 - 0 + 1));
    tesla.moveRight.bind(tesla, t)()
}, 800);

Правда, непонятно, чего вы хотели сказать выражением Math.random() * (200 - 0 + 1) вместо Math.random() * 199. Возможно, вы имели в виду что-нибудь типа Math.random() * 200 + 1.

Итог:

'use strict';
let Car = function(x, y) {
  this.x = x;
  this.y = y;

  this.spead = 40;

  this.draw();
};

Car.prototype.draw = function() {
  let carHtml = '<img src="http://nostarch.com/images/car.png">';

  this.carElement = $(carHtml);

  this.carElement.css({
    position: 'absolute',
    left: this.x,
    top: this.y
  });

  $('body').append(this.carElement);
};


Car.prototype.moveRight = function(distance) {
  this.x += distance;

  this.carElement.css({
    left: this.x,
    top: this.y
  });

};



let tesla = new Car(20, 20);
let nissan = new Car(300, 70);


setInterval(() => {
    let t = Math.floor(Math.random() * (200 - 0 + 1));
    tesla.moveRight.bind(tesla, t)()
}, 800);
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

→ Ссылка
Автор решения: Anton Shchyrov

Вынести t в анонимную функцию

setInterval(function() {
  let t = Math.floor(Math.random() * (200-0+1));
  tesla.moveRight(t);
}, 800);
→ Ссылка