How to play a sound at random time in javascript - javascript

I have this sound:
a = new Audio('audio.mp3');
and when I want to play it I use a.play()
How can I play this at random times?

Try this:
(function loop() {
var rand = Math.round(Math.random() * (3000 - 500)) + 500; // A random value between 3 and 500 seconds
setTimeout(function() {
a.play(); // Play the audio
loop(); // Call the loop function again
}, rand);
}());
Source: this question.

setInterval and Math.random() are what you are looking for.
a = new Audio('audio.mp3');
window.setInterval(function () {
a.play();
}, Math.random() * 500);

Related

How to end interval used to call function which updates time with Howler.js

I have made a function UpdateTime(x) which updates gets the current and total time of a song and writes in inside a div.
I call this function on onload (Howler.js), so it writes 0:0/song:time when the song is loaded and on onplay (Howler.js) with an interval every 50 miliseconds so it automatically updates the time when I start playing the song.
My problem is that this will cause an endless loop and effect performance.
My question is: How do I end that endless loop when the song stops playing?
If any of you have a more elegant approach to updating the time with Howler.js I would also appreciate it.
var songname = new Howl({
src: ['mp3/songname.mp3'],
onload: function() {
UpdateTime(songname);
},
onplay: function() {
setInterval(function(){
UpdateTime(songname);
},50);
}/*,
onend: function() {
maybe end the interval here?...
}*/
});
function UpdateTime(x){
let a = (x.seek()).toFixed();
let a2 = Math.floor(a / 60);
let a1 = a - a2 * 60;
let b = (x.duration()).toFixed();
let b2 = Math.floor(b / 60);
let b1 = b - b2 * 60;
document.getElementById("time").innerHTML=a2+":"+a1+" / "+b2+":"+b1;
}
This is a bug, but not surly the solution of your issue:
Here you assign a string to b (toFixed() returns a string):
let b = (x.duration()).toFixed();
And here you try to divide a string by 60.
let b2 = Math.floor(b / 60);
The result is undefined.
var durationUpdater;
var song = new Howl({
// song is still missing bunch of stuff here, but irrelevant for this issue
onplay: function() {
durationUpdater = setInterval(function(){
UpdateT1();
console.log(currentsong + ': song-progress updated');
},500);
},
onend: function() {
clearInterval(durationUpdater);
}
});

typescript - calling function at random intervals in ionic

I would like to repeatedly call the changeStyle() function at random intervals
here is my code so far:
this.platform.ready().then(() => {
this.myFunction()
});
myFunction() {
var min = 5,
max = 10;
var rand = Math.floor(Math.random() * (max - min + 1) + min); //Generate Random number between 5 - 10
this.changeStyle()
setTimeout(this.myFunction, rand * 1000);
}
changeStyle() {
console.log('changing style');
this.sensorImage = 'path/to/image1';
setTimeout(() => {
this.sensorImage = 'path/to/image2';
},
2000);
}
the relevant html code is
<img id='35' (click)="changeStyle()"
src="{{sensorImage}}">
ideally what this should do is call the changeStyle() function repeatedly and randomly without any input from me. however, I get a runtime error saying:
'TypeError: this.changeStyle is not a function. (In 'this.changeStyle('')', 'this.changeStyle' is undefined)'
Can you update your setTimeout(this.myFunction, rand * 1000); function to,
setTimeout(this.myFunction.bind(this), rand * 1000);
I believe the issue is related to this context.
You could do something like this,
changeStyle() {
...
...
const randomMilliSeconds = Math.floor( Math.random() * 10 ) * 1000;
setTimeout(() => {
this.changeStyle();
}, randomMilliSeconds)
}
You just need to call changeStyle once, manually or using click event and it will call itself at random intervals.

How to stop a function after ten seconds?

I found this piece of code while trying to find out a way to load a reddit page so that I can use ctrl + f to find a specific post. The problem is that it just keeps scrolling down and loading the pages. I need to find a way to stop it after 10 seconds so that I can take a look at what I loaded. Also I don't know any javascript so I couldn't really find anythig that would help me.
Here is the code
var lastScrollHeight = 0;
function autoScroll() {
var sh = document.documentElement.scrollHeight;
if (sh != lastScrollHeight) {
lastScrollHeight = sh;
document.documentElement.scrollTop = sh;
}
}
window.setInterval(autoScroll, 100);
I just paste that into the firefox console.
The setInterval() function returns an ID, which you can use to stop it.
Just put it in setTimeout() method like this:
var myInterval = setInterval(autoscroll, 100);
setTimeout(function(){ clearInterval(myInterval); }, 10000);
To stop the interval after a certain amount of time use a setTimeout() that calls clearInterval(). Here's a simplified version (with the time reduced to 1 second for demo purposes) that should help:
function autoScroll(){
console.log("running")
}
// save a reference to the interval handle
let interval = window.setInterval(autoScroll, 100);
// cancel interval after 1 second (1000 ms)
setTimeout(() => clearInterval(interval), 1000)
You will simply need to call clearInterval on your looped function to stop it after using a setTimeout set to 10 seconds, here is how you can implement it :
var lastScrollHeight = 0;
function autoScroll() {
var sh = document.documentElement.scrollHeight;
if (sh != lastScrollHeight) {
lastScrollHeight = sh;
document.documentElement.scrollTop = sh;
}
}
const interval = window.setInterval(autoScroll, 100);
window.setTimeout(() => {clearInterval(interval)}, 10000);
....
var intervalID = window.setInterval(autoScroll, 100);
setTimeout(function(){
clearInterval(intervalID);
}, 10000);
You can use setTimeout to call the function until 10s are up.
Here's an immediately-invoked function that calls itself every 100th sec until 10s has been reached.
(function autoScroll(t) {
t = t || 0;
if (t < 10000) {
console.log(t);
setTimeout(autoScroll, 100, t += 100);
}
})();

HTML5 Video with random speed - autorefresh

So, I want to play a video as a loop, while random values of playbackRate is created to randomly set speed up and down video during another random interval of time.
For that, I have this:
window.onload = function ()
{
var tempo = Math.floor(Math.random() * 3) + 0.5; // TIME TO SET VIDEO SPEED
var tempo2 = Math.floor(Math.random() * 2000) + 1000; // TIME TO SET INTERVAL TIME
setInterval(function ()
{
document.getElementById("my-video").playbackRate = tempo;
console.log(tempo , tempo2);
}, Math.floor(Math.random() * this.tempo2) + 600);
};
For some reason, the video is randomly speed up and down, as I expected, but I need to refresh page to change value.
JSFIDDLE
Thanks
You need to update the tempo variable in the setInterval function
setInterval(function ()
{
document.getElementById("my-video").playbackRate = tempo;
tempo = Math.floor(Math.random() * 3) + 0.5;
console.log(tempo , tempo2);
}, Math.floor(Math.random() * this.tempo2) + 600);
But I think that what you want is also an update of the tempo2 variable, by using a setTimeout call of a function that update the random values, use the tempo2 as new timeout.
var update = function () {
document.getElementById("my-video").playbackRate = tempo;
//update random values
tempo = Math.floor(Math.random() * 3) + 0.5;
tempo2 = Math.floor(Math.random() * 2000) + 1000;
console.log(tempo, tempo2);
//recall the method with new tempo2 value
setTimeout(update, tempo2);
}
See there:
JSFiddle

Adding start delay

function moveto(coordinates) {
step1 = coordinates[0];
step2 = coordinates[1];
var w = $(document).width();
var h = $(document).height();
$( "#full" )
.animate({left: -(step1 * w)}, 2000 )
.animate({top: -(step2 * h) }, 500 );
}
var randomNum = randomNumbers();
moveto(randomNum);
I need to add start delay of this function and to replay after a certain time
Change this:
var randomNum = randomNumbers();
moveto(randomNum);
To:
function doRandomMove(){
var randomNum = randomNumbers();
moveto(randomNum);
}
setTimeout(function(){
doRandomMove()
setInterval(doRandomMove, 10 * 1000);
}, 1000);
This will first call the change at 1 second, and keeps repeating after 10 seconds after first call.
Try this window.setTimeout("moveto(1,2)", 1000);.
Your function will be called with a delay of 1000ms.

Categories

Resources