JSFiddle - React, Tailwind, and code Playground
HTML
<div class="block1">Блок 1</div>
<div class="block2">Блок 2</div>
<span>0 миллисекунд</span>
CSS
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
}
div {
width: 100px;
height: 100px;
position: absolute;
color: white;
text-align: center;
line-height: 100px;
}
.block1 {
top: 0;
left: 0;
background: red;
}
.block2 {
bottom: 0;
right: 0;
background: blue;
}
span {
width: 100%;
height: 100%;
text-align: center;
line-height: 100vh;
display: block;
}
JavaScript
var block1 = document.querySelector(".block1");
var block2 = document.querySelector(".block2");
var time = document.querySelector("span");
var timer = null, startTime, counter = 0, state = false;
function stopCounter () {
state = false;
counter = 0;
clearTimeout(timer);
}
function runCounter () {
state = true;
timer = setTimeout( function()
{
console.log("работает когда требуется...");
if (!state) return;
counter++;
time.innerHTML = counter + " миллисекунд";
runCounter();
}, 1);
}
block1.onmouseout = runCounter;
block2.onmouseout = stopCounter;