How to use setTimeout with a "do while" loop in Javascript? - javascript

I'm trying to make a 30 second countdown on a span element (#thirty) that will be started on click of another element (#start). It doesn't seem to work. I would appreciate your help.
var countdown = function() {
setTimeout(function() {
var i = 30;
do {
$("#thirty").text(i);
i--;
} while (i > 0);
}, 1000);
}
$("#start-timer").click(countdown());

use this :
var i = 30;
var countdown = function() {
var timeout_ = setInterval(function() {
$("#thirty").text(i);
i--;
if(i==0){
i = 30;
clearInterval(timeout_);
}
}, 1000);
}
$("#start-timer").click(countdown);

Related

How to create a screensaver in javascript

I want to create a screensaver in JavaScript but I don't know how can I set the time between the images,.
I have an Ajax call and I see if the time is, for example, 2s or 90s, but I don't know how to set that time between images, this is my code:
var cont = 0;
var time = 1000
setInterval(function() {
console.log(tiempo);
if(cont == imagenes.length){
return cont = 0;
}else{
var imagen = imagenes[cont].imagen;
$('#imgZona').attr('src', imagen);
var time = imagenes[cont].tiempoVisible;
finalTime = Number(time);
}
cont++;
}, Number(finalTime ));
but the time between images is always the same, 1000, how can I change it for the time that I receive in the Ajax call? Which is imagenes[cont].tiempoVisible
I cannot comment as I don't have enough reputation, but take a look at this fiddle
https://jsfiddle.net/kidino/4mbpR/
var mousetimeout;
var screensaver_active = false;
var idletime = 5;
function show_screensaver(){
$('#screensaver').fadeIn();
screensaver_active = true;
screensaver_animation();
}
function stop_screensaver(){
$('#screensaver').fadeOut();
screensaver_active = false;
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
$(document).mousemove(function(){
clearTimeout(mousetimeout);
if (screensaver_active) {
stop_screensaver();
}
mousetimeout = setTimeout(function(){
show_screensaver();
}, 1000 * idletime); // 5 secs
});
function screensaver_animation(){
if (screensaver_active) {
$('#screensaver').animate(
{backgroundColor: getRandomColor()},
400,
screensaver_animation);
}
}
It will change background-color on idle mouse for 5 seconds, you can replace the code to change image, instead of background color.
Control set every timeout on each iteration.
var cont = 0;
var time = 1000
function next () {
console.log(tiempo);
if(cont == imagenes.length){
cont = 0;
}
var imagen = imagenes[cont].imagen;
$('#imgZona').attr('src', imagen);
cont++;
setTimeout(next, Number(imagenes[cont].tiempoVisible));
}
setTimeout(next, Number(initialTime));
Also I fixed a frindge condition.

How to make a setInterval wait until another one finishes?

How, when I click "one" link, make the second counter wait until the first one finishes and then count up to 14 (as instructed on line 155)?
https://jsfiddle.net/c4khk69f/27/
The function responsible for "one" link is function progressSim() on line 43.
$('a').on('click', function(e) {
e.preventDefault();
jQuery('.canvasmotherwrap').hide();
jQuery('.canvasmotherwrap').fadeIn();
al = 0;
al2 = 0;
window.clearInterval(sim1_1);
window.clearInterval(sim1_2);
window.clearInterval(sim2);
var storedata = $(this).attr('data');
console.log(storedata)
window[storedata]();
});
var sim1_1;
var sim1_2;
var sim2;
window.one = function() {
sim1_1 = setInterval(progressSim, 10);
sim1_2 = setInterval(progressSim, 1000);
}
window.two = function() {
sim2 = setInterval(progressSim2, 10);
}
I'm not entirely sure I understand what you are after, but I think you want two counters and when the "first" one has finished then the second should start and count to "14".
I hope this helps:
function doWork(targetDiv, startTime, countTo, onDone) {
var ticker = setInterval(function(){
diff = (((Date.now() - startTime) / 500) | 0);
targetDiv.innerText = diff;
if(diff < countTo){ return; }
clearInterval(ticker);
if(typeof(onDone) === 'function') { onDone(); }
}, 100);
}
var divFoo = document.getElementById("foo");
var divBar = document.getElementById("bar");
// your on "click"
doWork(divFoo, Date.now(), 5, function(){
doWork(divBar, Date.now(), 14);
});
<table><tr>
<td><div id="foo">0</div></td>
<td><div id="bar">0</div></td>
</table>

if body has class Fade in mp3 sound else fade out

I am trying to fade the volume of an mp3 in to 1 if the body has the class fp-viewing-0
How ever this isn't working and the volume doesn't change how can I fix this?
Code:
var audio0 = document.getElementById('audio-0');
audio0.volume = 0;
setInterval( function(){
if ($("body").hasClass("fp-viewing-0")) {
audio0.animate({volume: 1}, 1000);
}
else {
audio0.animate({volume: 0}, 1000);
}
}, 100);
HTML
<audio id="audio-0" src="1.mp3" autoplay="autoplay"></audio>
I've also tried:
$("#audio-0").prop("volume", 0);
setInterval( function(){
if ($("body").hasClass("fp-viewing-0")) {
$("#audio-0").animate({volume: 1}, 3000);
}
else {
$("#audio-0").animate({volume: 0}, 3000);
}
}, 100);
Kind Regards!
I have changed the jquery animate part to a fade made by hand. For that i created a fade time and steps count to manipulate the fade effect.
var audio0 = document.getElementById('audio-0');
audio0.volume = 0;
if ($("body").hasClass("fp-viewing-0")) {
audio0.volume = 1; //max volume
var fadeTime = 1500; //in milliseconds
var steps = 150; //increasing makes the fade smoother
var stepTime = fadeTime/steps;
var audioDecrement = audio0.volume/steps;
var timer = setInterval(function(){
audio0.volume -= audioDecrement; //fading out
if (audio0.volume <= 0.03){ //if its already inaudible stop it
audio0.volume = 0;
clearInterval(timer); //clearing the timer so that it doesn't keep getting called
}
}, stepTime);
}
Better would be to place all of this in a function that receives these values a fades accordingly so that it gets organized:
function fadeAudio(audio, fadeTime, steps){
audio.volume = 1; //max
steps = steps || 150; //turning steps into an optional parameter that defaults to 150
var stepTime = fadeTime/steps;
var audioDecrement = audio.volume/steps;
var timer = setInterval(function(){
audio.volume -= audioDecrement;
if (audio.volume <= 0.03){ //if its already inaudible stop it
audio.volume = 0;
clearInterval(timer);
}
}, stepTime);
}
Which would make your code a lot more compact and readable:
var audio0 = document.getElementById('audio-0');
audio0.volume = 0;
if ($("body").hasClass("fp-viewing-0")) {
fadeAudio(audio0, 1500);
}

Confused about SetInterval and closures

How can we repeatedly update the contents of a div using setInterval
I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?
but i have got few questions here
Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
How can we make it run infinitely, with the following code it gets stopped once i reaches 10.
window.onload = function() {
var timing = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
timing.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
i = 0;
return;
}
}, 1000);
}
<div id="timer"></div>
I am confused about setIntervals and closures
can some one help me here
Thanks
You could do something like this with a closure. Just reset your i value so, you will always be within your given range.
window.onload = function() {
var updateContent = (function(idx) {
return function() {
if (idx === 10) {
idx = 0;
}
var timing = document.getElementById("timer");
timing.innerHTML = idx++;
}
})(0);
var interval = setInterval(updateContent, 1000);
}
<div id="timer"></div>
This one should be clearer.
function updateTimer() {
var timer = document.getElementById("timer");
var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
if (timerValue == 10) {
timerValue = 0;
}
timer.setAttribute("data-timer-value", timerValue);
timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>

JQuery Auto Click

I have a problem, I have 3 button lets say it's called #pos1, #pos2 and #pos3.
I want to makes it automatically click #pos1 button in 2 seconds, after that click the #pos2 after another 2 seconds, and #pos3 after another 2 seconds,
after that back to the #pos1 in another 2 seconds and so on via jQuery.
HTML
<button id="pos1">Pos1</button>
<button id="pos2">Pos2</button>
<button id="pos3">Pos3</button>
Anyone can help me please?
Try
$(function() {
var timeout;
var count = $('button[id^=pos]').length;
$('button[id^=pos]').click(function() {
var $this = $(this);
var id = $this.attr('id');
var next = parseInt(id.substring(4), 10) + 1;
if( next >= count ){
next = 1
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
$('#pos' + next).trigger('click');
}, 2000);
})
timeout = setTimeout(function() {
$('#pos1').trigger('click');
}, 2000);
})
var posArray = ["#pos1", "#pos2", "#pos3"];
var counter = 0;
setInterval(function() {
$(posArray[counter]).triggerHandler('click');
counter = ((counter<2) ? counter+1 : 0);
}, 2000);
That should do the trick, though you did not mention when you want it to stop running.
Well I don't know what you already have but technically it could be done via triggerHandler()
var currentPos = 1,
posCount = 3;
autoclick = function() {
$('#pos'+currentPos).triggerHandler('click');
currentPos++;
if(currentPos > posCount) { currentPos = 1; }
};
window.setInterval(autoclick,2000);
If I have understood you question right, you need to perform click in a continuous loop in the order pos1>pos2>pos3>pos1>pos2 and so on. If this is what you want, you can use jQuery window.setTimeout for this. Code will be something like this:
window.setTimeout(performClick, 2000);
var nextClick = 1;
function performClick() {
if(nextClick == 1)
{
$("#pos1").trigger("click");
nextClick = 2;
}
else if(nextClick==2)
{
$("#pos2").trigger("click");
nextClick = 3;
}
else if(nextClick == 3)
{
$("#pos3").trigger("click");
nextClick = 1;
}
window.setTimeout(performClick, 2000);
}
This is quite buggy but will solve your problem.
using setInterval()
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
var tempArray = ["pos1", "pos2", "pos3"]; //create an array to loop through
var arrayCounter = 0;
setInterval(function() {
$('#' + tempArray[arrayCounter ]).trigger('click');
arrayCounter = arrayCounter <2 ? arrayCounter +1 : 0;
}, 2000);
fiddle here
check your console for fiddle example

Categories

Resources