Good day. I “beat” with my head for several hours and think how to make the timer start when you hover over the block, and the reverse is started after the cursor is withdrawn from the block. I need so that the class number_1 is added when you hover over the block, second two_2, etc. . (this is all easily solved using setTimeout) But it is necessary that if a person led the cursor over a block area, a countdown would begin. That is, if the last one was number_4, he would start to delete classes, after 1 second number_4, after 2 number_3, etc.

  • This is all easily solved with setTimeout - Grundy
  • Can you give an example? I understand that this through setTimeout is solved, but so far I can not understand how. I tried several ways, but I can’t adequately stop and start after hovering / outputting the cursor to / outside the block area - lingvo

1 answer 1

Please - https://jsfiddle.net/knvnckbz/4/

var div = document.querySelector('div'), addTimeout = null, removeTimeout = null, classNames = []; div.addEventListener('mouseover', addClass); div.addEventListener('mouseout', removeClass); function addClass() { clearTimeout(removeTimeout); var className = 'number_' + (classNames.length); div.classList.add(className); classNames.push(className); addTimeout = setTimeout(addClass, 1000); } function removeClass() { clearTimeout(addTimeout); var className = classNames.pop(); if (!className) return; div.classList.remove(className); removeTimeout = setTimeout(removeClass, 1000); } 
 div { width: 100px; height: 100px; background: black; } .number_1 { background: red; } .number_2 { background: blue; } .number_3 { background: yellow; } 
 <div> </div>