Pause the setInterval function on hover and continue when mouse is moved away

I'm encountering an issue while trying to tweak some code I already have. My goal is to stop the setInterval function when the mouse hovers over div id "mine" and then resume it when the mouse moves away from the div. Despite my efforts throughout the day and night, I can't seem to make it work properly. Any assistance on this matter would be highly appreciated. Thank you.

jQuery(document).ready(function(){

// select all checkboxes
jQuery(this).on('click', '#selectall', function() {
  jQuery('.checkbox').prop('checked', jQuery(this).is(":checked"));
});

    // perform AJAX request
    jQuery(this).on('submit', 'form[name="dispatchform"]', function(){
        jQuery.ajax({
            url: jQuery(this).attr('action'),
            data: jQuery(this).serialize(),
            type: 'post',
            beforeSend: function(){jQuery('body').css('opacity', '0.5');},
            success: function(data) {
                var response = jQuery(data).find('#dispatchTable').html();
                jQuery('#dispatchTable').html(response);

                // display message
                var msg = jQuery(data).find('td.messageStackError, td.messageStackSuccess').html();
                jQuery('#msg').css({
                    'padding': '10px',
                    'text-align': 'center',
                    'font-size': '12px',
                    'background-color': 'darkkhaki',
                    'margin': '10px 0',
                    'color': '#fff'
                }).html(msg);
            },
            complete: function(){jQuery('body').css('opacity', '1');}
        });
        return false;
    });

          setInterval(function() {
      jQuery.ajax({
            url: jQuery(this).attr('action'),
            data: jQuery(this).serialize(),
            type: 'post',
            beforeSend: function(){jQuery('body').css('opacity', '0.5');},
            success: function(data) {
                var response = jQuery(data).find('#dispatchTable').html();
                jQuery('#dispatchTable').html(response);

                // show message if available
                var msg = jQuery(data).find('td.messageStackError, td.messageStackSuccess').html();
                if(msg !== undefined) {
                jQuery('#msg').css({
                    'padding': '10px',
                    'text-align': 'center',
                    'font-size': '12px',
                    'background-color': 'darkkhaki',
                    'margin': '10px 0',
                    'color': '#fff'
                }).html(msg);
                }
            },
            complete: function(){jQuery('body').css('opacity', '1');}
        });
    }, 15000);

});

Answer №1

I'm uncertain about the specific location where you wish for that to occur...

What I am trying to convey is that I do not observe div#mine within that code, so it is unclear whether it should be contained within one of them, outside all of them, or both inside and outside under particular circumstances...

...regardless, the fundamental concept is as follows:

var doSomethingId;

function doSomething ( ) { }

var mine = document.querySelector("#mine");
mine.addEventListener("mouseover", function () {
    doSomething();
    doSomethingId = setInterval(doSomething, 10000);
});

mine.addEventListener("mouseout", function () {
    clearInterval(doSomethingId);
});

This essentially summarizes the process. The jQuery alternative does not differ significantly.

The crucial aspect is to store the ID (var id = setInterval(/*...*/);) and utilize it for clearing the interval (clearInterval(id);).
Rather than "restarting" the interval, you need to call id = setInterval(...); again, transforming the id into the new interval to halt it.

Edit:

This might be an instance of an "XY" dilemma...
Meaning that you seek a solution to a problem which is not fundamentally the root issue, but rather a secondary concern layered on top of the core problem.

A quick illustration:
I usually navigate through most forms by tabbing in, moving through the fields with tabs, and then pressing ENTER or tabbing down to hit the submit button followed by ENTER.

In this scenario (for individuals using keyboards/touchscreens, etc.), the initial issue still remains unresolved for now.

However, if you are open to making some adjustments, the resolution can be similar.

To elaborate, instead of your `setInterval(function () { jQuery./.../ });

Consider implementing something like this;

var shouldUpdate = true,
form  = this,
$mine = jQuery("#mine");

$mine.on("mouseover", function () { shouldUpdate = false; });
$mine.on("mouseout",  function () { shouldUpdate = true;  });

// complete setInterval(function () { jQuery.ajax(...); }); copied and pasted here, including the `if`
function submitForm () {
    if (!shouldUpdate) { return; }
    jQuery.ajax(/* ... */);
}

var submitId = setInterval(submitForm, 15000);
// clearInterval(submitId); -- just remember to set the new ID, if you restart it

As demonstrated, there is no longer a necessity to initiate and terminate the interval.
An if statement is utilized to exit whenever I am in a state where updates are unnecessary (ideally, it should go further and terminate any ongoing XHR queries if you start editing a field).

Answer №2

After checking out this article, it seems like you're interested in achieving something similar to this:

<!DOCTYPE html>
<html>
<head>
<style>
#custom{
    width:300px;
    height:300px;
    border:1px solid blue;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Timer:</p>
<div id="custom"></div>
<div id="countdown">
</div>

<script>

jQuery(document).ready(function(){
    $( "#custom" )
    .mouseleave(function() {
        enableTimer();
    })
    .mouseenter(function() {
        disableTimer();
    });
});

var count=15;
var timerActive = true;
var countdown=setInterval(timer, 1000); //updates every second

function timer(){
  if (timerActive)
    count--;

  if (count == 0){
     alert('execute action here!');
     count = 15;
  }

  $('#countdown').text(count);
}

function enableTimer(){
    timerActive = true;
}
function disableTimer(){
    timerActive = false;
}
</script>

</body>
</html>

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

Transferring information from one webpage to another using AJAX or embedding it with an iframe

I recently received an address with a basic HTML structure containing numbers. I attempted to display it using an iframe, which worked when tested separately but encountered a connection refusal error when embedded in my page. Alternatively, I tried AJAX ...

Tips for designing a dropdown menu for selecting the number of passengers

Looking for guidance on adding a passenger count dropdown form similar to the one in the image below. I've searched everywhere but can't find a demo or any help. Can someone assist me with this? https://i.sstatic.net/RO1vi.jpg Appreciate any he ...

Transforming an image into a geometric shape using html and css - step by step guide

Hey fellow stackoverflow users! I've created a geometric figure using multiple divs for an unconventional website design. However, I'm struggling to adapt images within these divs because the original width is not being maintained. When you view ...

Guide to aligning a URL in an HTML file

Greetings all, I'm new to HTML and struggling with how to center a URL on my webpage. For example: <a href="http://www.google.com"> Click Here to Open Google </a> I attempted using the tag and the STYLE attribute but without success. ...

Benefits of Utilizing Object.create

Unlike the referenced question, this code snippet is sourced from the book "JavaScript: The Definitive Guide". It introduces an inherit method that applies Object.create if available, but falls back to traditional JavaScript inheritance when it's not. ...

ClickAwayListener's callback function stops executing midway

I am currently utilizing Material-UI's ClickAwayListener in conjunction with react-router for my application. The issue I have come across involves the callback function of the ClickAwayListener being interrupted midway to allow a useEffect to run, on ...

The Angular Animation constantly resets with each new action taken

In my Angular project, I am working on a scaling animation for a list. I want the animation to only trigger when specific buttons (red and green) are pressed. Currently, the animation restarts regardless of what I click on. Can anyone help me troubleshoot ...

Retrieving data from the <script> tag and transferring it to the t-esc tag within Odoo 12

After attempting to retrieve the current coordinates of a location in Odoo, I successfully obtained longitude and latitude data through an alert generated by the following code: <button onclick="getLocation()">Try It</button> ...

Obtain both the key and value from an Object using Angular 2 or later

I have a unique Object structure that looks like this: myCustomComponent.ts this.customDetails = this.newParameter.details; //the custom object details are: //{0: "uniqueInfo", // 5: "differentInfo"} The information stored in my ...

Using jQuery to create tabs and display or hide tab-like content

I'm looking for a simpler way to achieve my goal without using the jQuery-UI library. Here is the setup, where I have navigation markup in the header: <ul> <li><a class="active" href="#" title="">Uno</a></li> <li& ...

Include a CSS counter style class that adds leading zeros

Looking for a way to increment a particular <p> style class (p.wp as an example) from 1 - n across multiple HTML pages. The challenge is that the number needs to have 4 digits, ranging from 0001 to 0117. #start_wp {counter-reset: WP 0;} p.wp{} p. ...

I find myself facing a roadblock in navigating Servlets and HTML

I'm currently immersed in a project aimed at launching an innovative online food ordering platform. To bring this vision to life, I've harnessed the power of HTML, CSS, and JavaScript for frontend development, Java (Servlets) for backend function ...

Combining data search for an element within an array

In my attempt to populate the contact field by fetching data from the collection companies.contacts, I am using the following code snippet. // COMPANY MODEL const objectContact = { name: { type: String, required: true }, email: { type: String, requir ...

What's inside the navigation bar, icons, and content cards? (Using HTML and Bootstrap)

Having a few issues that need resolving: Unable to display the contents of my navbar after the navbar-brand section. Looking to add a home button, about section with a drop-down menu including: 'Our mission', 'our team', & ...

Update the "select" element's "option" value upon redirection from another page

I have a webpage called Page A, where I have three anchor links. Then there is also Page B, where I have a select dropdown with the options 30, 180, and 365. What I want to achieve is that when I click on one of the anchor links on Page A (which have href ...

Text is not wrapping onto a new line following the <hx> elements

I've been struggling to get my paragraph text to start on a new line after the subtitles in my code. I've tried using display:block and adding a right margin to take up the full width of the div, but nothing seems to be working! If you want to s ...

Testing a feature in Angular that modifies a variable

Trying to test a function that updates a Boolean variable has been causing some confusion for me. The strange thing is, even though the function seems to be called successfully when using the toHaveBeenCalled method, the variable itself never actually gets ...

Adding Zod validation for elements within an array in a React TypeScript application

Currently, I am utilizing Zod validation to confirm whether a given value is an email and also checking for the minimum length. However, I'm encountering an issue where if the field is left empty and the submit button is clicked, it displays the "requ ...

Adjust the placement of a dropdown menu placed within a table

I have successfully implemented a sticky table header, but I am encountering an issue with the select element integrated into my table: View before scrolling the table View after scrolling the table As you can see, the select element overlaps with the t ...

Implementing Google Maps JS API with Inertia.js server-side rendering: A beginner's guide

Setting up server-side rendering for my Vue.js SPA using Inertia and Laravel has been a challenge. Every time I attempt to load a page with a Map, an error from the SSR server process occurs: [Vue warn]: Unhandled error during execution of setup function ...