Avoiding overlapping in setTimeOut when using jQuery.hover()

Looking to trigger an effect one second after the page loads, and then every 3 seconds in a loop. When the user hovers over a specific element with the ID #hover, the effect should pause momentarily. It should then resume 2 seconds after the user stops hovering.

Encountering issues with overlapping sounds and animations, especially when quickly hovering and unhovering over the element. What could be causing the problem with my code? (Link to Code)

var test;
function hoverTest(arg) {
  if (arg == 'stop') {
    clearTimeout(test);
  }
  if (arg == 'start') {
    playSound();
    $('#hover').transition({
      opacity: 0,
      duration: 1000,
      complete: function() {
        $('#hover').transition({
          opacity: 1,
          duration: 1000,
          complete: function() {
            test = setTimeout(function() { hoverTest('start'); }, 3000);
          }
        });
      }
    });
  }
}

$('#hover').hover(function() {
  hoverTest('stop');
}, function() {
  setTimeout(function() {
    hoverTest('start');
  }, 2000);
});

function playSound() {
  var sound = new Audio('sound.mp3');
  sound.play();
}

setTimeout(function() {
  hoverTest('start');
}, 1000);

Answer №1

Make sure to copy and paste this code into a new file, then run that HTML file.

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<style>
    #hover {
        width: 100px;
        height: 100px;
        background: red;
    }
</style>
<div id="hover"></div>

<script type="text/javascript">
var interval = null;
var hoverTest = function(method){
    playSound();
    $("#hover").fadeOut(1000, function() {
        $(this).fadeIn(1000);
    });

}
var playSound =function() {
    var sound = new Audio('http://www.sounddogs.com/previews/25/mp3/306470_SOUNDDOGS__an.mp3');
    sound.play();
}

$(document).ready(function(){
    interval = setInterval('hoverTest()',3000);
    $("#hover").mouseenter(function(){
        clearInterval(interval);
    }).mouseleave(function(){
        interval = setInterval('hoverTest()',3000);
    })
})

</script>

Answer №2

One solution is to insert the line "clearTimeout(test);" at the beginning of the hoverTest function. For example:

var test;
function hoverTest(arg) {
  clearTimeout(test);
  if (arg == 'stop') {
    clearTimeout(test);
  }
  if (arg == 'start') {
    playSound();
    $('#hover').transition({
      opacity: 0,
      duration: 1000,
      complete: function() {
        $('#hover').transition({
          opacity: 1,
          duration: 1000,
          complete: function() {
            test = setTimeout(function() { hoverTest('start'); }, 3000);
          }
        });
      }
    });
  }
}

Answer №3

Give this a shot: (make sure to reset the timer first)

$('#hover').hover(function() {
  hoverCheck('halt');
}, function() {
  clearInterval(timer);
  setTimeout(function() {
    hoverCheck('begin');
  }, 2000);
});

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

Retrieve data with remote JSON to enable autocomplete functionality

I am experiencing some difficulties with the .autocomplete function. Here is my current code: <script type="text/javascript"> $( ".search" ).autocomplete({ source: [{label:'link label1', searchLink:'http://link1.com'}, ...

Problem with jQuery image gallery

Currently, I am in the process of creating a simple image gallery that enlarges an image when it is clicked. To achieve this functionality, I am utilizing jQuery to add and remove classes dynamically. $(".image").click(function() { $(this).addClass("b ...

Scroll-triggered closing of modals in Next Js

I have integrated a Modal component into my Next.JS application, and I have implemented a functionality to close the modal when the user scrolls outside of it. However, this effect is also triggering when the user scrolls inside the modal. How can I modi ...

Placing a div with position:absolute inside another div with position:absolute and turning them into position:fixed

HTML <div class="box1"></div> <div class="box2"> <div class="box3"></div> </div> CSS Properties of box1, box2 and box3 are: box1 { position: absolute; z-index: 100; background-color: rgba(39, 39, 39, 0.3) ...

css problem with scaling in firefox

My goal is to create a website that adjusts its size based on the document size. When the document size is between 0px and 1024px, I want the design to be responsive. This can easily be achieved with CSS media queries. Similarly, when the document size is ...

Discover each *distinct arrangement* from a given array

I'm looking to generate unique combinations of element positions in a JavaScript array. Here's the array I am working with: var places = ['x', 'y', 'z']; The combinations I want are: [0,1], [0,2], [1,2]. Current ...

Preserving the video's aspect ratio by limiting the width and height to a maximum of 100%

I am trying to integrate a YouTube video using their embed code in a "pop-up". However, I am facing an issue where the video does not resize to fit within the height of its parent. I want it to be constrained by the div#pop-up that contains the video. Curr ...

What is the best way to update the content of a modal using jQuery and AJAX?

Despite previous inquiries on this matter, none of the answers provided have been helpful to me. Therefore, I am addressing the issue again... I am currently developing the frontend of a website that does not involve any backend functionality (no server c ...

Hinting the type for the puppeteer page

I am trying to type hint a page variable as a function parameter, but I encountered a compilation error. sync function than_func(page:Page) ^ SyntaxError: Unexpected token: ...

Struggling with passing data to a child component in React

I am currently working on a gallery project where users can click on an image to view it in a separate component using props. The images are sourced from a hardcoded array, and the challenge lies in connecting this data to the component accurately. I have ...

Issues with calculating SUM in MySQL within a Node.js Express application using EJS template

I am currently working on developing a dashboard for my Node.js project. The aim is to calculate the sum of certain values for an overview. While the SELECT statement works fine in my MySQL database, when I incorporate it into my Node project, I do not rec ...

Move from right to left on the slide?

Is there a way to toggle a div's visibility between collapsed and expanded, transitioning smoothly from right to left? I've noticed that most examples I come across demonstrate the transition from left to right. ...

Send the user authentication form to a different location by using an AJAX request

I am in the process of developing a .Net Web application using ASP MVC, jQuery & AJAX. Within this application, I have a list of products. When a user clicks on the detail button of a specific product, they are taken to a details view which includes an "Ad ...

Implement a dropdown menu for filtering, but it is currently not functioning as expected

When I select a city_name, my goal is for the graph to only display information pertaining to that particular city. In the params section of my code, I have included filtering options using a selection menu in Vega-Lite. However, despite selecting Brisba ...

Troubleshooting Images in a React Application Integrated with WordPress API

I am struggling to understand why this GET request is consistently returning a 404 error. I have thoroughly tested the URL using Postman and everything seems to be in working order for the title and excerpt, but the images are causing some issues. Does a ...

Is there a way for me to update a Link To containing a parameter by using history.push with a parameter inside a table cell?

Hey there! I'm working on some code and wondering if it's doable to replace the Link To with a history.push, including the following parameter, like so: <TableCell style={{width: '10%'}}> <Link to={`/run-id/${item.run_ ...

Discovering the current page URL in jQuery Mobile

I am struggling to retrieve the current page URL in a jQuery Mobile website (using the default ajax navigation). My latest attempt involves binding to the `pagecreate` event, but unfortunately it does not seem to work for any pages that are injected into ...

Angular tutorial: Organizing data by date only

This is my first time building an Angular app. I am fetching JSON data from an API using a factory service to get football match fixtures. My goal is to group these fixtures by date while disregarding the time component. The date string in the JSON is fo ...

What could be causing express to have trouble finding the ejs file in the views directory?

Recently delved into the world of learning NodeJS and Express. // Working with express framework var express = require("express"); var app = express(); app.get("/", (req,res) => { res.render("home.ejs"); }) //Setting up port listening app.listen ...

An error occurred while trying to load the resource in the Redux-Saga: connection refused

Utilizing axios allows me to make calls to the backend server, while redux-saga helps in managing side effects from the server seamlessly. import {call, put, takeEvery} from "redux-saga/effects"; import {REQUEST_FAILED, REQUEST_SUCCESS, ROOT_URL, SUBMIT_U ...