How to calculate the clamping time?

  • 0
    I am doing a mini web game for practice, and I need to make a control for the div.
    I came up with such a solution: when you click on a block (4 in total: up, down, left, right), start the timer, the value of which is written into a variable, which in turn is substituted into style.margin = variable + 'px';
    In general, how to do this without libraries?
    JavaScript Anonymous, Oct 22, 2020

  • 2 Answers
  • 0
    you don't need a timer for this purpose. it is enough to remember the current time at the moment of pressing, and at the moment of releasing from the current time, subtract the memorized one.

    // переменная, в которую запоминаем время
    let pressedTime =;

    // при нажатии
    pressedTime =;


    // при отжатии
    const passedTime =;
    console.log("С момента нажатия прошло", passedTime, "миллисекунд");
    console.log("С момента нажатия прошло", passedTime/1000, "секунд");

    // при отрисовке внутри цикла window.requestAnimationFrame(loop);
    if( кнопка нажата ){
    const passedTime =;
    style.margin = (parseInt(style.margin)+passedTime/100) + 'px';

    if you need more accurate time than milliseconds, then instead of () use () < br />

    Well, here's another look for the implementation of the game loop ru / docs / DOM / window.r ...

    Here's a simple version:


  • 0

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!