Stop jQuery timeout when mouse hovers over a div

I'm currently dealing with a class:

<ul class="topStatsWrapper">
    <li><a href="">link</a></li>
    <li><a href="">link</a></li>
    <li><a href="">link</a></li>
</ul>

This particular ul class is set to update every 3 seconds. I'm looking for a solution on how to pause this automatic update when the mouse hovers over the .topStatsWrapper class, and resume it once the mouse leaves. Any ideas would be greatly appreciated. Thanks!

initialize: function() {
    window.setTimeout( _.bind( this.updateStats, this, true ), 3 * 1000);
},

If you need to view the full code, you can access it here: http://pastebin.com/nGnfaeN5

Answer №1

It appears that the information provided may not be sufficient to give a precise response. I recommend assigning your setTimeout function to a variable that can be cleared upon hovering over your class.

var timer; // defined globally

// within your function
initialize: function() {
    timer = setTimeout( _.bind( this.updateStats, this, true ), 3 * 1000);
},

Next, utilize an event listener:

$(document).on("mouseover", ".myclass", function(){
    clearTimeout(timer);
});

Consider using setInterval instead:

var timer; // defined globally

// within your function
initialize: function() {
    timer = setInterval( function(){ ... your code ... }, 3000);
},

Again, employ an event listener:

$(document).on("mouseover", ".myclass", function(){
    clearInterval(timer);
});

Answer №2

Revise your updateStats function like so...

updateStats: function() {

    if (window._noUpdate === true) return;

    var that = this, update;
    this.showLoading( true );

    update = $.when( update,
        that.ajax( 'getTopics', null, '.newestThreads' ),
        that.ajax( 'getPosts', {limit: JSON.stringify([0, 3])}, '.newestPosts' )
    );

    update.done( function() {
        that.showLoading();
        window.setTimeout( _.bind( that.updateStats, that, true), that.interval * 1000);
    });

}

Modify your initialize function like this...

initialize: function() {
    this.interval = parseInt($('.topStatsWrapper').attr('data-topstats-interval'));
    window.setTimeout( _.bind( this.updateStats, this, true ), 3 * 1000);
    $("body").on("hover", ".topStatsWrapper",
        function() {
            window._noUpdate = true;
        },
        function() {
            window._noUpdate = false;
        }
    });
},

This change introduces a global variable (_noUpdate) to indicate if the cursor is over the ul. If it's true, the update function will halt execution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

showcase fresh material using the jquery fancybox

I have a fancybox popup using jQuery that is functioning as intended. Inside the popup, there is a link <a href="http://example.com/foo/bar.html">show another content of this fancybox</a> However, when you click on the link, the fancybox disap ...

Steps to position an image without a background in the middle of a smaller container:

My HTML includes the following code: <div style="width:400px;height:300px;overflow:hidden;"> <img src="http://d39kbiy71leyho.cloudfront.net/wp-content/uploads/2016/05/09170020/cats-politics-TN.jpg" /> </div> Take a ...

Typescript/Three.js encounters the issue of game objects becoming undefined

Something in my code seems to have broken unexpectedly. I can't figure out why the "Game" object is defined before calling this.render() in the constructor, but becomes undefined in the render method. Before render(), the console shows: Game camera: ...

Tricks for disabling _blank behavior in jquery?

I'm currently integrating a widget into a webpage using PHP. The widget contains jQuery code that causes all links to open in an external page. Is there a way to override or disable this code so it doesn't impact every link on the page? My prefe ...

The focal point on the canvas is off-center during image rotation

I am looking to achieve image rotation around its center on a canvas. EXPECTED: The image should rotate at its center CURRENT RESULT: The image rotates in a circular motion The code includes: A sprite class that creates a sprite and returns it. An ani ...

Ways to display or conceal a textbox depending on the choice made from a dropdown list

I'm a beginner in using jquery. I'm trying to create a dropdown menu with different options. When "Others" is selected from the dropdown, I want a text box to be displayed. Can someone provide guidance on how to achieve this? Here is the code sni ...

Unable to display the full height of the browser

Having trouble achieving full browser height with my jQuery code. Check out this link for more information -- Below is the snippet of my HTML code: <div class="container contentContainer"> <div class="row"> ...

Guide to testing Vuex Mutations with Vue-test-utils and Jest

I have reviewed a few tutorials on mocking and testing Vuex actions, but I have struggled to implement them successfully on my own. Despite following the steps outlined in the links provided, I consistently encountered an issue where toHaveBeenCalled would ...

Creating Visuals with CSS Gradients: A Tutorial on Generating Images and SVG Files

I currently have a CSS gradient applied and I am interested in creating an image or SVG file from it. However, I am unsure of how to accomplish this task. Any advice would be greatly appreciated. background: -webkit-linear-gradient(bottom, rgb(211, 208, ...

The CSS properties of 'hidden' mimic those of 'flex'

On my website, I have a logo that is hidden until the screen reaches a certain size. Despite using both "flex" and "hidden" classes for styling, I am encountering an error suggesting that they do the same thing. Removing either class disrupts the intende ...

What is stopping me from utilizing ES6 template literals with the .css() method in my code?

I am currently working on a project where I need to dynamically create grid blocks and change the color of each block. I have been using jQuery and ES6 for this task, but I am facing an issue with dynamically changing the colors. Below is the snippet of m ...

What is the best way to target the first child element in this scenario?

Is there a way to target only the p tag with id="this" using .root p:first-child selector? Here is the code snippet: Link to CodePen .root p:first-child { background-color: green; } p { margin: 0; } .container { display ...

Header spanning the entire width with varying ends

Hello everyone, I'm currently working on a website and struggling to create a header similar to the image shown above. I want the header to span the full width of the page. Can anyone provide guidance on achieving this using HTML5/CSS3 without relyin ...

content organized in tabs using the fancybox feature

I am attempting to dynamically load content using AJAX with fancybox. It loads fine, but the tab won't change if I use the default function or via AJAX. However, if I use fancybox and set the type to 'iframe,' it loads and alternates tabs p ...

How can I retrieve a list of dynamic dropdown/selectbox options using JavaScript and Laravel?

I am facing an issue with a dynamic dropdown field in my update form modal/popup within Laravel 5.2. The dropdown list works only in the first row, and when I add more dropdowns, the lists do not show up because I am unsure how to implement foreach in the ...

Converting phone numbers with conditional tests to regular expressions

After reviewing different regex phone formats, I found that mine is a bit unique. Rather than using existing patterns, I decided to write my own code to format phone numbers as the user types using the keyup function in jQuery. While I used some basic rege ...

Adding content to a text field and then moving to the next line

I am looking to add a string to a text area, followed by a new line. After conducting some research, here are the methods I have attempted so far but without success: function appendString(str){ document.getElementById('output').value += st ...

Deactivate Search Functionality for Users who are not Logged in on an Angular 2 Application

The login component and view are functioning as intended, preventing users from accessing AuthGuard protected routes if they're not logged in. However, I'm facing a challenge with the search bar displayed on the home login screen (actually presen ...

When invoking a JavaScript method, the context variable 'this' is lost

I have developed a basic pointer to a method like this: export class SmbwaService { getExistingArsByLab(labId: number): Observable<SmwbaAr[]> { this.otherMethod(); } otherMethod(): void { } } let method: (x: number) => ...

$http promise chain executing in an incorrect sequence

As a beginner in angularjs, my objective is straightforward. I aim to execute an ajax request to fetch data and, upon completion, I want to initiate a second call to retrieve another set of data based on the information from the initial set. To achieve th ...