Using a setInterval loop in Javascript to play an audio clip can lead to off-beat rhythms and occasional dropouts, especially

I attempted to play a very small and short mp3 file (5kb, 200ms) using JavaScript and looping it with setInterval. It functions smoothly on desktop browsers without any issues.

However, when I try to play the same file on a mid-range android phone (both browser and app webview), as well as android emulators such as Nox player and Android Studio Emulator, it sometimes skips during playback. Additionally, the rhythm is not consistent and there are delays of a few milliseconds at times.

If I switch to an even smaller audio file (1kb, 100ms), the skipping issue disappears but the timing is still inconsistent. The code I am using is quite simple (see below). Can you suggest any optimizations to ensure it plays with precise timing and without dropping?

var tap_sound = new Audio("/audio/tap2.mp3");
tap_looping_Job = setInterval(() => {
        tap_sound.play();
    }, 400);

Answer №1

The issue at hand here revolves around the difference in execution times across different platforms.

Using setInterval to manage playing audio can lead to problems if the interval is faster than the actual execution time. It's possible for setInterval to be triggered again before the previous sound has finished playing, causing the strange behavior you're experiencing.

Due to the faster CPU on desktops, this issue may not have been as noticeable there compared to mobile devices.

A simple solution or test would be to increase the interval time until it works seamlessly on mobile without any glitches.

Another drawback of using setInterval is that even if you set it to wait for 400ms, it might actually take longer, like 600ms, due to JavaScript's single-threaded nature. Your delay essentially acts as a request to JavaScript, which it will fulfill after the specified time but not necessarily immediately.

An improved approach would involve utilizing requestAnimationFrame within a loop, calculating the delta time between each frame, and triggering the sound once the delta reaches the target time, such as 400ms. This method aims for more precise timing.

You can find a helpful explanation on this topic on this website: How setInterval works in JavaScript

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

Is it possible to transmit the survey findings through a telegram?

Just finished creating a survey using the platform . Here are the results: Data format: {"question1":["item1"],"question2":["item2"],"question3":["item2"],"question4":["item2" ...

Error encountered in jQuery call during Page_Load

Here is the code I am using to register a javascript function on Page_Load (I also tried it on Page_Init). This javascript function switches two panels from hidden to shown based on a parameter when the page loads: protected void Page_Load(object sen ...

Exploring the possibilities of Three.JS by manipulating the world position of a child 3D object

I have a child object3D that is part of a group Object3D. While the child object's position is displayed relative to the parent object's space, I am trying to change the location of the child object within the 3D space. To do this, I first need t ...

Obtain every possible sequence of US phone number segments for a provided number

The format of a US phone number is as follows: (XXX) XXX-XXXX Given a string consisting only of digits with a length between 0 and 10, I want to generate an array of all possible chunks that match the US phone number format. For example: Input: "54" Out ...

Switch up the placement of the boxes by moving them in different directions, such as

I've been attempting to recreate the button movement demonstrated in this link , but I'm having trouble achieving it. Using CSS animation, I can make the buttons move in a straight line, here's what I have so far: <div id="box" style=&ap ...

I am disappointed with the functionality of .innerHTML as it is not displaying the API data as desired

Currently working on an exercise that requires utilizing the following API: https://raw.githubusercontent.com/Laboratoria/LIM011-data-lovers/master/src/data/potter/potter.json. The task involves creating an input field where a character's name can be ...

Exploring the full potential of MongoDB with Discord.js through a single entry point

I'm currently facing an issue with a command that checks someone else's balance within my economy system. The problem is that it only stores one user's data at a time. So, when the database is empty and the bot tries to create a profile for ...

Encountering an error with requireJS: "Unknown provider $routeProvider with AngularJS 1.2.9 ngRoute"

Currently, I am utilizing angularJS-1.2.9 and angular-route-1.2.9 to configure routes for my application. Additionally, I have integrated requireJS as the dependency loader to modularize the code. Despite adding the ngRoute dependency into the AngularJS co ...

Execute a specialized function with imported modules and specified parameters

Within an npm project, I am looking to execute a custom function with arguments, or ideally provide it as a script in the package.json file like this: npm run custom-function "Hello, World". Currently, I have a file called src/myFunction.ts: import * as e ...

Reading environment variables in Next.js (specifically in an Azure App Service)

We need to deploy the identical image to various environments (development, quality assurance, production). Our nextjs application is deployed on Azure app service and we intend to retrieve azure app settings as part of the configuration. We are unable t ...

Smooth scrolling feature malfunctioning in mobile view

While working on my website, I noticed that the smooth-scroll feature works perfectly on desktop browsers. However, on mobile devices, when I click on a link, it does not scroll to the correct position. It always ends up much lower than expected. Any idea ...

Having trouble getting a basic jQuery UI tooltip to function properly

I attempted to recreate the demo found on this website: http://jqueryui.com/tooltip/#default Here is the HTML code I used: <h3 title='this is the title of hello world'>hello world</h3> And here is the JavaScript code: $(document). ...

Changing a variable in an HTML file using a JavaScript file

I am working with JavaScript code that has been imported from another file containing a variable that I need to update in my HTML file. Is there a way to update the variable without directly inserting the JavaScript code into my HTML document? JavaScript ...

glyph containing an undesirable space filled in

I have a character that I want to draw. The outline is correct but the filling isn't showing up as expected. Take a look at the comparison below (1. is what I want, 2. is what I currently have): c.beginPath(); //draw the curves c.closePath(); c.fi ...

The button refuses to navigate to a URL upon being clicked

Struggling with my JavaScript buttons. Currently, they are functioning flawlessly, but I am attempting to change my "Order Online" button into a link that opens a new window to a Menufy menu page. Unfortunately, I can't seem to crack the code on how t ...

Problem with Angular: ng-show not constantly re-evaluating expression

Utilizing a variable named activeScope to manage the state and toggle between two forms. This variable updates its value when a tab is clicked, triggering changeScope. While the change in active states for the tab buttons registers correctly, the divs for ...

What is the process for configuring the global warning level in ESLint?

My current setup involves using WebStorm and the ESLint configuration provided by Airbnb. I'm curious if there is a way to have ESLint errors displayed in a more subtle manner instead of the harsh red color, or perhaps make all ESLint rules warnings ...

Countdown with precision! This timer will begin at the one-hour mark

Having an issue with my JavaScript stopwatch. When I hit the start button, the stopwatch immediately shows one hour (01:00:00) before counting normally. Any solutions to prevent this instant start at one hour would be highly appreciated. Thank you in adv ...

When utilizing the "nofollow/sponsored" attribute, window.open will open in a new window as opposed to a new tab

When using a window.open link with the "nofollow" attribute, I expect it to open in a new tab. However, it opens in a new window instead. This code successfully opens in a new tab: $('.b_link').click(function (e) { e.preventDefau ...

Adjust the template within a directive to dynamically include an additional directive

Challenge Create a custom directive that dynamically adds the ng-bind attribute, allowing for the use of ng-bind, ng-bind-html, or ng-bind-html-unsafe without needing to manually add it to the template definition throughout. Illustrative Example http://j ...