ClearTimeout eliminates flashing instance code, cleartimeout instance
Definition and usage
The clearTimeout () method can cancel the timeout set by the setTimeout () method.
Syntax
clearTimeout(id_of_settimeout)
Parameters |
Description |
Id_of_settimeout |
The ID value returned by setTimeout. This value identifies the delayed execution code block to be canceled. |
Requirement: When you place the cursor over the parent menu, the sub-menu below is displayed. When you move the cursor from the sub-menu or parent menu, you need to collect the sub-menu. The final result is as follows:
PS: this requirement is very common. The most common practice is to nest another Ul element under the li element to include the child element. This method can be completely controlled with css. However, the sub-menu is separated from the navigation bar today. The header-tags block is displayed when you move the cursor over the product.
<Ul class = "header-nav"> <li class = "nav-item home"> <a href = "@ Url. action ("Index", "Home ") "> homepage </a> </li> <li class =" nav-item products "id =" header_tags "> <a href =" # "> product <span class = "icon-caret-down"> </span> </a> .... </li> </ul> <div class = "header-tags"> <ul> <li> <p> all </p> </li> <li tagid =" 4 "> <p> sofa </p> </li> <li tagid =" 3 "> <p> seat </p> </li>... </div>
This cannot be fully controlled with css (hover can only control child or sibling elements ).
/* Parent and Child */# a: hover # B {display: block}/* sibling */# a: hover + # B {display: block}
The above situation requires scripts. Here the # header_tags and. header-tags elements are involved. When you move the mouse to # header_tags and. header-tags, The moveout event of # header_tags cannot be triggered immediately when the mouse moves to. header-tags, but the tags must be displayed continuously. The sub-menu is collected only when the cursor is left from # header_tags and. header-tags.
$(function () {var tagsTime;$(document).on('mouseover mouseout', '#header_tags', function(event){var $headerTagsBox = $('.header-tags');if (event.type == 'mouseover') {clearTimeout(tagsTime);$headerTagsBox.slideDown(300);}else if (event.type == 'mouseout') {tagsTime = setTimeout(function(){$headerTagsBox.slideUp(200);}, 200);}});$('.header-tags').hover(function(){clearTimeout(tagsTime);},function(){var $me = $(this);tagsTime = setTimeout(function(){$me.slideUp(200);}, 200);}); });
If the timer is not cleared and the execution is delayed, the navigation bar will continue to flash. You cannot click.
Articles you may be interested in:
- Analysis of setTimeout () and clearTimeout () usage examples in js