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

Arranging a child element within a parent element by placing the child div on the right side of the parent div

I am struggling with positioning a child .div containing rotating images to the right side of its parent (header) .div. I am utilizing the flexbox model for layout purposes. Despite my efforts, the solutions I have come across so far have not yielded the ...

Retrieve the unfinished user input from React's Material UI Autocomplete

I've implemented Material UI's Autocomplete input with react-hook-form as shown below: import React from "react"; import {Controller} from "react-hook-form"; import {Autocomplete} from "@mui/material"; export const ...

Tips on effortlessly updating the URL of your website

Despite seeing the question asked multiple times, I still find myself struggling to understand how to modify a URL or create a new HTML page that seamlessly integrates into a website without redirecting users. I am curious about achieving the functionalit ...

Customizing Javascript for Mouse Exiting Browser Window

I have implemented a JavaScript function on my website to display a lightbox when the visitor's mouse goes beyond the browser window. You can check it out here: [http://mudchallenger.com/index-test2.html][1] However, there seems to be an issue where ...

Troubleshooting: AngularJS Http Post Method Failing to Execute

I am attempting to make an HTTP POST request to update my database using AngularJS. Although my code is not displaying any errors, the database is not being updated and I'm having trouble pinpointing the issue. Below is the code snippet: //topic-serv ...

Unable to connect to node.js webserver using the godaddy shared hosting URL

Upon entering www.example.com:3000 into my browser, I am encountering the following error message (where 'example' represents my domain name) This site can't be reached - www.example.com took too long to respond. I have taken the following ...

What is the best way to create a dynamic information page using both V-for and V-if in Vue.js?

Hey everyone, I recently attempted to set up this layout: This company offers a variety of services grouped into different categories, each containing sub-options and specific details. This is how my JSON data is structured: { "services& ...

Utilizing React Typescript for Passing Props and Implementing them in Child Components

I'm currently working with React and TypeScript and attempting to pass data as props to a child component for use. However, I've encountered an error that I can't quite understand why it's happening or how to resolve it. Additionally, I ...

Having trouble setting the `variant='dense'` for material-ui Toolbar – it remains at a height of 64px no matter what

Implemented a hello world AppBar/Toolbar with the variant='dense' style. import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import registerServiceWorker from './registerServiceWo ...

Delete an entry from the localStorage

I am attempting to create a basic To-Do list using jQuery, but I have encountered an issue. This is my first time utilizing localStorage. After setting up the structure for my To-Do list, I wanted the items to remain visible when I refresh the page. Initia ...

Insert more text following the existing content

Is it feasible to include text using pseudo-elements ::after or ::before to a specific word? For example, I am interested in placing a PDF icon consistently beside the word "Download". [PDF] Download Alternatively, are there other methods available? ...

"Obtaining mouse coordinates in VueJS: A step-by-step guide

I am using a component that is activated by v-on:click="someMethod". Is there a way to retrieve the X and Y coordinates of the mouse click within this component? Extra context: The component I'm working with is an HTML5 Canvas element. ...

Do not allow nested objects to be returned

I am facing an issue with typeorm, where I have a queryBuilder set up like this: const projects = await this.conn.getRepository(UserProjectRelations).createQueryBuilder("userProject") .innerJoin("userProject.userId", ...

Switching back and forth between two different numbers with the help of React.useState hooks

Can someone help me with the logic using React.useState hooks? I'm trying to toggle the "volume" option in the state of the "PlayOn" object between 0 and 0.75. I am not very experienced with React. I need help with the function logic for soundChange ...

Let's explore further - delving into JSON & array manipulation using the foreach loop in Pure JavaScript

Although I have some experience with Java Script, I still consider myself a beginner in certain areas, particularly when it comes to accessing JSON objects and arrays. I've tried various syntax and options for accessing arrays using [], but so far, I ...

The :contains method in jQuery functions smoothly in Firefox, Safari, and Chrome, but unfortunately does not work

My code on JSFiddle is having some compatibility issues with the jQuery :contains selector specifically in Internet Explorer versions 7, 8, and 9. The code works fine in Firefox, Safari, and Chrome. You can find the working code here. I tried making the ...

Creating objects in separate JavaScript files and including them in the main file, along with their

Following the creation of a config.js file with an object named contextTokenObject, modifications and additions need to be made to this context object from another file (specifically when creating a passport strategy). In the 'passport.js' file, ...

Is there a way to access a computed property within methods?

Currently, I am utilizing this particular package to implement infinite scrolling in Vue. In order to continuously add new elements during each scroll, I fetch JSON data from my API server and store it in a data object. Subsequently, I divide the array in ...

The ng-bind directive is functional when used with a textarea element, but it does not work with

Recently diving into the world of angularjs, I stumbled upon ng-bind and its interesting functionality when used as a directive for textarea: <input type="text" ng-model="review.start"/> <textarea ng-bind="review.start"> </textarea> I ...

Implementing the ability to add and remove classes in JavaScript

I am trying to implement an add or remove class feature in JavaScript, but I'm facing some issues with it. Below is the code snippet I have: if (window.location.hash == "#/profile/"){ document.getElementById("tabMenu").removeClass("bottomTa ...