-2

I've watched Udemy video. The instructor created a basic car race with jQuery. When the race is over, it shows the result of race and writes which car is the first and second. However, I don't understand how the function knows which car came in first? How does the function know which place is first and second? Can someone say how does "Complate" work?

$("#race").click(function() {
  // This function I don't understand

  function Check() {
    if (Complate == false) {
      Complate = true;
    } else {
      place = "second";
    }
  }

  // Find  Car width

  var CarWidth1 = $("#car1").width();
  var CarWidth2 = $("#car2").width();

  // Find stop places
  var WayWidth = $(window).width() - CarWidth1;
  var bottomWidth = $(window).width() - CarWidth2;

  // Find speed     
  var carTime1 = Math.floor((Math.random() * 5000) + 1);
  var carTime2 = Math.floor((Math.random() * 5000) + 1);

  //Place
  var place = "first";

  // This one 
  var Complate = false;

  $("#car1").animate({
    left: WayWidth

  }, carTime1, function() {
    Check();

    $("#span1").text("Finished in " + place + " place and clocked in at " +
      carTime1 + " milliseconds")
  });

  $("#car2").animate({
    left: bottomWidth

  }, carTime2, function() {
    Check();

    $("#span2").text("Finished in " + place + " place and clocked in at " +
      carTime2 + " milliseconds")
  });
});
  • Use a debugger, set breakpoints, and see for yourself. https://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code – Heretic Monkey Jul 11 '19 at 18:39
  • @said-mammadli welcome to stackoverflow.com :). Don't mind if at first you get a few -1 votes on your question. You're perfectly fine. Try to pay attention to positive comments posted on your question, they can help you solve your problem faster. Good luck! – urig Jul 11 '19 at 19:11

1 Answers1

1

This script works around the jQuery .animate-function. You can find the documentation here. The animate function takes a function that is executed when the animation is complete. For both cars it calls the Check function, which knows based on Complate if a car has already finished. Since we only have two cars, the car that does not finish in first will finish in second.

You can debug this yourself by putting a debugger statement in certain parts of the code. In particular, it should be interesting to put debugger calls in front of both Check() calls, and step through the code. This allows you to figure out which values are in which variables.

Please note that the code in this example is not all that great. This example does not scale up to more cars for example. There are also variables available that make it much easier to determine who was in first place, as we calculate the time it takes for each car to reach the finish line in the function itself. Last but not least, function names and variable names are normally always in camelCase.

Sumurai8
  • 20,333
  • 11
  • 66
  • 100