Is it possible to repeat a loop every 10 minutes in Javascript? - javascript

I would like to have this loop ( a song) executed and then wait for 10 Minutes,before it will repeat itself.
for (i = 0; i < 3; i++) {
var audio = document.createElement("");
audio.src = "my_sound.mp3";
audio.play();
};
It would be great if someone could help me.

Try using this:
setInterval(function() {
for (i = 0; i < 3; i++) {
var audio = document.createElement("audio");
audio.src = "my_sound.mp3";
audio.play();
}
}, 600 * 1000);

It easily can be done like this:
function play () {
for (i = 0; i < 3; i++) {
var audio = document.createElement("audio");
audio.src = "my_sound.mp3";
audio.play();
};
}
setInterval(play, 600000);
//the function name. do not put () after it as you aren't executing it.
//600000 is the number of milliseconds in 10 minutes.
play(); //this will execute it immediately the first time if you want.
setInterval

You're looking to use setInterval() or setTimeout
http://www.w3schools.com/jsref/met_win_setinterval.asp
The first one, executes every X time, the second one executes after X time has passed, wich one to use depends on how infinite is your loop or if you want to exit it sometime, for wich you can evaluate in setTimeout before execution or use clearInterval() for the other one.

Create a function that calls itself after a timeout and call it once
function createAudioElement() {
for (i = 0; i < 3; i++) {
var audio = document.createElement("audio");
audio.src = "my_sound.mp3";
audio.play();
};
setTimeout(createAudioElement, 600000);
}
createAudioElement();
Make sure to specify what element to create in document.createElement()- in this case audio, otherwise it will throw an error.

You can using setTimeout() or setInterval(), but you cannot count on it being precisely 10 minutes because the function will get queued in the event loop and will only fire after its timeout time has been reached and the JavaScript runtime is idle.
setTimeout() takes a callback function as its first argument and a number (in milliseconds) to wait as its second. Think of the number as the "minimal amount of time to wait" until the timeout function is invoked.
function go(){
// Clear the previous timer
timer = null;
for (i = 0; i < 3; i++) {
var audio = document.createElement("audio");
audio.src = "my_sound.mp3";
audio.play();
}
// Re-run the timer
timer = setTimeout(go, 600000);
}
var timer = setTimeout(go, 600000);
Or, with setInterval():
var timer = setInterval(function(){
for (i = 0; i < 3; i++) {
var audio = document.createElement("audio");
audio.src = "my_sound.mp3";
audio.play();
}
}, 600000);

Related

clearTimeout(timer) not taken into account - New timer variable created each time

In the current slideshow I'm building, I use a timer variable to rotate the slides automatically every 4s. Since manual controls are also present, I wanted to reset this timer whenever the controls are used to avoid any premature succession between two slides, but didn't manage to do it.
I supposed it to be a scope problem, but the timer variable is out of the functions that are trying to share it (showSlide(n) and changeSlide(n)). Yet a brand new timer variable seems to be created each time the changeSlide function is called : the slides automatic rotation quickens each time the "next" control is used, as if multiple timeouts were calling the function simultaneously. What is wrong here ?
const slideshows = document.getElementsByClassName("js-slideshow");
[].forEach.call(slideshows, function(slideshow) {
slideshowlize(slideshow);
});
function slideshowlize(slideshow){
const desc = slideshow.getElementsByClassName("js-desc");
const slide = slideshow.getElementsByClassName("js-slide");
let timer;
let index = 0;
const slidePrev = slideshow.querySelector('.js-prev');
const slideNext = slideshow.querySelector('.js-next');
function showSlide(n){
clearTimeout(timer); // This one is not used yet
if(n < 0){
n = slide.length -1;
}
else if(n > slide.length -1){
n = 0;
}
let i;
for(i = 0; i < slide.length; i++){
slide[i].classList.remove("is-shown");
}
for(i = 0; i < desc.length; i++){
desc[i].classList.remove("is-shown");
}
slide[n].classList.add("is-shown");
desc[n].classList.add("is-shown");
index = n;
timer = setTimeout(function(){
changeSlide(1);
}, 4000);
}
function changeSlide(n){ // this is where the magic doesn't happen
clearTimeout(timer);
if (n > 0){
showSlide(index += 1);
} else {
showSlide(index -= 1);
}
timer = setTimeout(function(){
changeSlide(1);
}, 4000);
}
showSlide(index);
slidePrev.addEventListener('click', function(){
changeSlide(-1);
});
slideNext.addEventListener('click', function(){
changeSlide(1);
});
}
Edit : Two different timers were set up. Since showSlide(n) were already resetting the timer, changeSlide(n) had no need to do it too. Thanks to Bergi for pointing it out.
function changeSlide(n){
//removed "clearTimeout(timer);"
if (n > 0){
showSlide(index += 1);
} else {
showSlide(index -= 1);
}
//removed "timer = setTimeout(...);"
}

Smoothly increase interval time with JS

How can i play a sound at an interval (for example once every second) and gradually decrease the time between the intervals?
At the moment, i use two intervals with setInterval, the first one plays the sound each second, the second setInterval speeds up the first interval every 20 seconds. This works, but it leaves a nasty "pause" between the intervals.
Is there a better way?
Example code (just to clarify, not necessary to read):
var audio = new Audio('track.wav');
var baseSpeed = 1000;
var myInt;
var changeInt;
//Starts a Run
function beatInterval() {
audio.play();
};
//Speeds up the other interval
function speedUpInterval() {
baseSpeed = baseSpeed - 20
clearInterval(myInt);
myInt = setInterval(beatInterval, baseSpeed);
console.log(baseSpeed);
myInt = setInterval(beatInterval, baseSpeed);
changeInt = setInterval(speedUpInterval, 20000);
You can delay adjustment of speed, until interval function is actually executed:
var speedChanged = false;
function beatInterval() {
if(speedChanged) {
speedChanged = false;
clearInterval(myInt);
myInt = setInterval(beatInterval, baseSpeed);
}
audio.play();
};
function speedUpInterval() {
baseSpeed = baseSpeed - 20
speedChanged = true;
console.log(baseSpeed);
}

How to run a javascript function X seconds?

I am using setInterval to run a Javascript function that generates a new, random integer in a div. the timer starts when I click on the div. I am having problems with stopping it form generating new numbers after five seconds.
Using setTimeout, I hide the div after 5 seconds; that stops random numbers, but I lose the div.
How can I efficiently stop the generating of numbers in the div, and not hide it?
HTML:
<div id="div" onmousedown='F();'>Click here</div>
JS:
function F(){
var div = document.getElementById("div");
setInterval(function(){
var number = Math.floor(Math.random()*28) ;
div.innerHTML = number;
}, 1000);
setTimeout(function(){
div.style.display = 'none';
},5000);
};
Just use a counter to keep track of the number of times the interval has ticked and then use clearInterval to stop it:
var count = 0;
var intervalID = setInterval(function() {
// generate your random number
count++;
if (count === 5) {
clearInterval(intervalID);
}
}, 1000);
Something hastily written, but what you want to do is keep track of your interval handle and then clear it. You can do this with a setTimeout
var forXsecs = function(period, func) {
var handle = setInterval(func, 1000);
setTimeout(function() { clearInterval(handle); }, period * 1000);
}
The timing is not perfect. Matt's answer would also work.
Another option is a slight change on Matt's answer that removes setInterval and just uses timeouts.
var count = 0;
var forXsecs = function(period, func) {
if(count < period) {
func();
count++;
setTimeout(function() {forXsecs(period, func);}, 1000);
} else {
count = 0; //need to reset the count for possible future calls
}
}
If you just want to simply let it run once each second and that 5 times you can do it like this:
HTML:
<div id="5seconds"></div>
JS:
var count= 0;
setInterval(function(){
if(count < 5){
document.getElementById('5seconds').innerHTML = Math.random();
count++
}
},1000);
This will generate a random number each second. until 5 seconds have passed
you should use clearInterval to stop the timer.
To do so, you pass in the id(or handle) of a timer returned from the setInterval function (which creates it).
I recommend clearing the interval timer (using clearInterval) from within the function being executed.
var elm = document.querySelector("div.container");
var cnt = 0;
var timerID;
function generateNumber()
{
cnt += 1;
elm.innerText = cnt;
if (cnt >= 5) {
window.clearInterval(timerID);
}
}
timerID = window.setInterval(generateNumber, 1000);
.container {display:block; min-width:5em;line-height:5em;min-height:5em;background-color:whitesmoke;border:0.1em outset whitesmoke;}
<label>1s Interval over 5s</label>
<div class="container"></div>

How can I stop this blinking effect?

I have a Javascript function that loops to create a blinking effect by replacing a button image.
function blinkit() {
intrvl = 0;
for (nTimes = 0; nTimes < 500; nTimes++) {
intrvl += 1000;
t = setTimeout("document.getElementById('imgshowreport').src='report_icon.png';",intrvl);
intrvl += 1000;
t = setTimeout("document.getElementById('imgshowreport').src='report_icon2.png';",intrvl);
}
}
This serves the purpose but when the button is clicked I want the blinking to stop. How can I do this without the whole page being refreshed?
Using break to terminate the loop is useless because your loop will already have concluded and set all the timeouts before the user can click the button.
It would be better to use setInterval once rather than queueing up hundreds of individual timeouts. Then you can kill the interval in one fell swoop.
You should also not use string code, but a function:
var myInterval = null;
function blinkit() {
var i = 0;
myInterval = setInterval(function() {
document.getElementById('imgshowreport').src = (i % 2) ? 'report_icon2.png' : 'report_icon.png';
i++;
}, 1000);
}
document.getElementById('imgshowreport').onclick = function() {
if (myInterval != null) {
clearInterval(myInterval);
myInterval = null;
document.getElementById('imgshowreport').src = 'report_icon.png';
}
};
I haven't tested it for typos, but the basic logic is right.
You can use the break syntax
break;
or
nTimes = 500;
Try break
http://www.w3schools.com/js/js_break.asp

Why is this javascript code making browser draw 50% CPU and so much memory?

I have this banner rotator code:
function ban_rot() {
//First preload images
// counter
var i = 0;
// create object
imageObj = new Image();
// set image list
images = new Array();
images[0] = "../Graphics/adv/1.gif"
images[1] = "../Graphics/adv/2.jpg"
// start preloading
for (i = 0; i <= images.length; i++) {
imageObj.src = images[i];
}
///////////////////////
var links = new Array("http://www.link1.com", "http://www.link2.se");
var alts = new Array("alt1", "alt2");
var titles = new Array("title1", "title2");
var counter = 0;
var banner_div = document.getElementById("ban_rot");
cycle();
function cycle() {
if (counter == links.length) {
counter = 0;
}
else if (counter < links.length) {
banner_div.innerHTML = '<img src=\"' + images[counter] + '\" border=\"1px\" style=\"border-color:#000;\" alt=\"' + alts[counter] + '\" title=\"' + titles[counter] + '\">';
//increase counter
counter++;
}
setInterval(cycle, 8000);
} //end cycle function
} //end ban_rot function
With this code, after around 2-3 minutes in Firefox or Chrome, the memory goes up and cpu goes to around 50%.
The computer gets laggy and I have to terminate Chrome and FF.
Is there any reason for this in this code above?
Thanks
Use setTimeout() instead of setInterval() here, like this:
setTimeout(cycle, 8000);
With setInterval() you're queuing more and more stacks of the function each time, rather than calling it once 8 seconds later, we're queueing another interval timer to run every 8 seconds, so you're getting this:
8 seconds: 1 run
16 seconds: 2 runs
24 seconds: 4 runs
32 seconds: 8 runs
...uh oh
With setTimeout() you'll get just one run when the timer is up, not an additional run every 8 seconds.
To be clear, this happens because you're calling it each time it runs, with normal one-time usage this wouldn't be an issue, there's nothing inherently evil with setInterval().

Categories