I was wondering if there is a way to set the setTimeout function to different timeout on the fly.
So, for example I check something every 1 second, but if I don't get an expected result in like 10 seconds I want to "reconfigure" this setTimeout to wait 3 seconds instead of 1.
Here is my code:
var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;
var waitForNewRace = setInterval(
function checkForNewRace(){
if ( $("#data").html() == "1"){
$("#res").html("got it!");
}
else{
$("#counter").html(br);
if (br++ > 9)
waitInterval = 3000;
}
$("#tst").html(waitInterval);
},
waitInterval
);
If you want to check it out here is the mentioned code on jsfiddle: http://jsfiddle.net/Hitman666/Vyczj/2/
You have to stop the interval and restart it. See this fork of your jsfiddle.
EDIT: I've copied your code here in case something happens with your jsfiddle code:
var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;
function checkForNewRace(){
if ( $("#data").html() == "1"){
$("#res").html("got it!");
}
else{
$("#counter").html(br);
if (br++ > 5){
clearInterval(waitForNewRace);
waitInterval += 1000;
if (waitInterval > 10000)
waitInterval = 10000;
waitForNewRace = setInterval(
checkForNewRace,
waitInterval
);
}
}
$("#tst").html(waitInterval);
}
var waitForNewRace = setInterval(
checkForNewRace,
waitInterval
);
I think this will do what you want:
var br = 0;
var waitForNewRace = setInterval(function(){
checkForNewRace();
if(++br == 9){
clearInterval(waitForNewRace);
setInterval(checkForNewRace, 3000);
}
}, 1000);
function checkForNewRace(){
if($("#data").html() == "1"){
$("#res").html("got it!");
clearInterval(waitForNewRace);
}else
$("#counter").html(br);
$("#tst").html(waitInterval);
}
You could use clearInterval:
var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;
var waitForNewRace = setInterval(checkForNewRace,
waitInterval
);
function checkForNewRace(){
console.log(waitForNewRace);
if ( $("#data").html() == "1"){
$("#res").html("got it!");
}
else{
$("#counter").html(br);
if (br++ > 9){
waitInterval = 3000;
clearInterval(waitForNewRace);
br = 0;
waitForNewRace = setInterval(checkForNewRace,
waitInterval
);
}
}
$("#tst").html(waitInterval);
}
fiddle: http://jsfiddle.net/Vyczj/5/
An alternative, just need to add two lines to your own code:
var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;
var waitForNewRace = setInterval(
function checkForNewRace(){
if ( $("#data").html() == "1"){
$("#res").html("got it!");
}
else{
$("#counter").html(br);
if (br++ > 9){
clearInterval(waitForNewRace);
waitInterval = 3000;
waitForNewRace=setInterval(checkForNewRace,waitInterval);
}
}
$("#tst").html(waitInterval);
},
waitInterval
);
Related
Currently, I am using an archaic method of setting a variable true at the start of the animation and false after the animation has played (see below.) I also think something might be wrong with how I process animations in the interval because when I add an animation to the array of animations to be processed, it isn't processed. Here's my code:
var animationDone = true;
function g_e(e){
return document.getElementById(e);
};
class Main{
constructor(){
this.animations = [];
this.tasks = [];
}
start_animating(){
var x = setInterval(function (){
if (animationDone == true){
try{
alert(this.animations[0]);
this.aminations[0].func(this.animations[0].args);
this.animations.shift();
}
catch(e){
}
}
},1);
}
add_animation(f, a){
this.animations.push({func:f, args:a});
alert("animation added");
}
start_working(){
var x = setInterval(function (){
try{
this.tasks[0].func(this.tasks[0].args);
this.tasks.shift();
}
catch(e){
}
},1);
}
animation_blink(){
var blink = 0;
window.setInterval(function blinking(){
if (blink == 0){
document.getElementById("blinker").innerHTML = ">";
blink= 1;
}
else if(blink == 1){
document.getElementById("blinker").innerHTML=" ";
blink = 0;
}
}, 1000);
}
animation_fade(object){
var fade = 0;
var fadeOut = 0;
animationDone = false;
var interval = setInterval(function startFade(){
g_e(object.element).style.opacity = fade;
if(fade>1 && fadeOut == 0){
fadeOut = 1;
}
else if(fade < 0){
clearInterval(interval);
}
else if(fadeOut == 0){
fade = fade + 0.2;
}
else if(fadeOut == 1){
fade = fade - 0.2;
}
}, 500);
animationDone = true;
}
plbl(object){
animationDone = false;
var p = plbl.intervals;
if (!p)
plbl.intervals = p = {};
if (p[object.destination])
clear();
function clear() {
clearInterval(p[object.destination]);
delete p[object.destination];
}
var i = 0;
var elem = document.getElementById(object.destination);
p[object.destination] = setInterval(function(){
checkChar = object.message.charAt(i);
if(checkChar =="|"){
elem.innerHTML += "<br>";
}
else{
elem.innerHTML += object.message.charAt(i);
}
i++;
if (i > message.length){
animationDone = true;
clear();
}
}, object.speed);
}
command(input){
alert(input);
if(input == "y"){
g_e("start").style.display = "none";
g_e("startUp").style.display = "block";
this.add_animation("test", "test");
}
}
get_input(){
var x = g_e("input").value;
g_e("input").value = "";
return x;
}
key_checker(event){
var key = event.keyCode;
if (key == 13){
this.command(this.get_input());
return false;
}
}
start(){
this.start_working();
this.start_animating();
this.animation_blink();
}
}
alert("compiled");
main = new Main();
main.start();
I need to stop the execution of the function PadanjeFun when ZivotBroj==-5.
I tried jQuery stop() Method, clearInterval(myVar) and return but it's not working.
I need to stop all tree animation (#cepJedan, #cepDva, #cepTri) when ZivotBroj==-5
Here is the code:
var PadanjeFun=function(){
if(bod==4) //Change speed when bod reaches the number
{
q=4;
}
else if(bod==7)
{
q=3;
}
$(document).ready(function(){
setInterval(function(){ //Neka zakasni prvi cep
$("#cepJedan").animate({
top: "850px",
},1000 * q, function(){
BodRacunaj();
document.getElementById("cepJedan").style.top = "150px";
ZivotOduzmi();
document.getElementById("Broj").innerHTML = bod;
});
}, 1000); //Let it start after 1 sec
});
$(document).ready(function(){
setInterval(function(){
$("#cepDva").animate({
top: "850px",
},1000 * q, function(){
BodRacunaj();
document.getElementById("cepDva").style.top = "150px";
ZivotOduzmi();
document.getElementById("Broj").innerHTML = bod;
});
}, 9000); //Let it start after 9 sec
});
$(document).ready(function(){
setInterval(function(){
$("#cepTri").animate({
top: "850px",
},1000 * q, function(){
BodRacunaj();
document.getElementById("cepTri").style.top = "150px";
ZivotOduzmi();
PadanjeFun();
console.log("Q je: "+q);
document.getElementById("Broj").innerHTML = bod;
});
}, 3000); //Let it start after 3 sec
});
}
Here is the ZivotOduzmi function if that helps anyone:
var ZivotOduzmi=function(){
if((document.getElementById("cepJedan").style.top == "850px") && (document.getElementById("box").style.left == "550px") || (document.getElementById("box").style.left == "980px"))
{
zivotBroj--;
console.log("Imate jos ovoliko zivota: "+zivotBroj);
var element = document.getElementById('Zivot');
element.style.width = (element.offsetWidth - 100) + 'px';
}
else if((document.getElementById("cepDva").style.top == "850px") && (document.getElementById("box").style.left == "120px") || (document.getElementById("box").style.left == "980px"))
{
zivotBroj--;
console.log("Imate jos ovoliko zivota: "+zivot);
var element = document.getElementById('Zivot');
element.style.width = (element.offsetWidth - 100) + 'px';
}
else if((document.getElementById("cepTri").style.top == "850px") && (document.getElementById("box").style.left == "120px") || (document.getElementById("box").style.left == "550px") )
{
zivotBroj--;
console.log("Imate jos ovoliko zivota: "+zivotBroj);
var element = document.getElementById('Zivot');
element.style.width = (element.offsetWidth - 100) + 'px';
}
}
You need to assign setInterval to a variable like:
var anim3;
$(document).ready(function(){
anim3 = setInterval(function(){
$("#cepDva").animate({
top: "850px",
},1000 * q, function(){
BodRacunaj();
document.getElementById("cepDva").style.top = "150px";
ZivotOduzmi();
document.getElementById("Broj").innerHTML = bod;
});
}, 9000); //Let it start after 9 sec
});
and call
clearInterval(anim3);
$("#cepDva").stop();
http://jsfiddle.net/Bwdfw/98/
is there a way to start timer only after a button is clicked in the given jsfiddle link
http://jsfiddle.net/Bwdfw/98/
var seconds=0;
var Score=0;
var index=0;
countdown(60);
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
Have a function inside the click handler and a variable which states if the function has started or not.
Also you can club the click events inside a single handler and the index can be stored as part of the data-* attributes which reduces duplicated code.
Javascript
//Timer //
var seconds = 0,
Score = 0,
index = 0,
timerStarted = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if (seconds > 60 && Score < 30) {
alert("Not enough Score");
}
if (seconds > 0) {
setTimeout(tick, 1000);
}
}
$("#one, #two, #three").click(function () {
if(!timerStarted) {
countdown(60);
timerStarted = true;
}
var dataIndex = $(this).data('index');
if (index == dataIndex) {
Score++;
if(dataIndex == 2) {
index = 0;
} else {
index++;
}
}
$("#score").html("Score: " + Score);
});
HTML
<div id="timer"></div>
<div id="score">Score: 0</div>
<button id="one" type="button" data-index="0">Button1</button>
<button id="two" type="button" data-index="2">Button2</button>
<button id="three" type="button" data-index="1">Button3</button>
Check Fiddle
var seconds=0;
var Score=0;
var index=0;
var started = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
$("button").click(function(){
if(!started){
started = true;
countdown(60);
}
});
You could generate custom event after click
$(window).trigger('clicked');
$(window).on('clicked', function() {
setTimeout(tick, 1000);
});
http://jsfiddle.net/Bwdfw/100/
Just remember to check if the countdown has not started yet.
$("button").click(function(){
});
This will add a handler to all the buttons in your DOM, then just check the status of the countdown.
Check this fiddle:
http://jsfiddle.net/eddiarnoldo/Bwdfw/102/
function animate(elem,style,from,to,time) {
if (!elem) return;
var start = new Date().getTime(),
timer = setInterval(function() {
var step = Math.min(1, (new Date().getTime() - start) / time);
elem.style[style] = (from + step * (to - from))+'px';
if (step == 1) clearInterval(timer);
}, 25);
elem.style[style] = from + 'px';
}
Here is my code. and i need to pause and play in it
Finally i found the answer
function animate(elem,style,to,time,callback)
{
if(!elem) return;
_animating = true;
curAnimElem = elem; /*stores the current Element*/
curStyle = style; /*stores the current style*/
curTo = to; /*stores the current to 'px'*/
curCallback = callback; /*stores the current callbak function*/
if(style === 'left'){ from = elem.offsetLeft; }
else if(style === 'top'){ from = elem.offsetTop; }
var start = new Date().getTime(),
animTimer = setInterval(function()
{
if(!pauseV)
{
pauseTime = Math.round(time - (new Date().getTime()-start));
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+'px';
if( step == 1 ){ _animating = false; clearInterval(animTimer); if(callback){callback(); callback = null;} }
}
else{clearInterval(animTimer);}
},25);
elem.style[style] = from + 'px';
}
the above code is to animate the elements(left or top only). to PAUSE and PLAY, include the below code in pause/play event function.
function pauseFun()
{
if(pauseV)
{
pauseV = false;
if(_animating){ animate(curAnimElem,curStyle,curTo,pauseTime,curCallback); }
}
else if(!pauseV)
{pauseV = true;}
}
Its works for me......
Thanks.
Use clearInterval(timer) to pause the animation and then timer = setInterval(...) again to resume it. You would need to break the setInterval callback out into its own named function (inside the body of the first function) to make resuming easier.
try this:
var doAnimation=true;
var timer=0;
var start=undefined;
function animate(elem,style,from,to,time)
{
if(!elem && doAnimation) return;
if(start==undefined)start = new Date().getTime();
timer = setInterval(function(){
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+'px';
if( step == 1){
doAnimation=false;
clearInterval(timer);
elem.style[style] = from+'px';
start=undefined;
}},25);
}
function fun(){
doAnimation=!doAnimation;
if(doAnimation){play();}
else{pause();}
}
function play(){
animate( document.getElementById('box'),'left',0 , 200, 7000);
}
function pause(){
clearInterval(timer);
}
$(document).ready(function(){
play();
});
Check out the fiddle here:
http://jsfiddle.net/sunnykumar08/V9MHN/1/
For practice I am trying to display a number that increments from 0 - 9, then decrements from 9 - 0, and infinitely repeats.The code that I have so far seems to be close, but upon the second iteration the setInterval calls of my 2 respective functions countUp and countDown seem to be conflicting with each other, as the numbers displayed are not counting in the intended order... and then the browser crashes.Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Algorithm Test</title>
</head>
<body onload = "onloadFunctions();">
<script type = "text/javascript">
function onloadFunctions()
{
countUp();
setInterval(countUp, 200);
}
var count = 0;
function countUp()
{
document.getElementById("here").innerHTML = count;
count++;
if(count == 10)
{
clearInterval(this);
countDown();
setInterval(countDown, 200);
}
}
function countDown()
{
document.getElementById("here").innerHTML = count;
count--;
if(count == 0)
{
clearInterval(this);
countUp();
setInterval(countUp, 200);
}
}
</script>
From 0 - 9, up and down: <div id = "here"></div>
</body>
</html>
You need to capture the return value from setInterval( ... ) into a variable as that is the reference to the timer:
var interval;
var count = 0;
function onloadFunctions()
{
countUp();
interval = setInterval(countUp, 200);
}
/* ... code ... */
function countUp()
{
document.getElementById("here").innerHTML = count;
count++;
if(count === 10)
{
clearInterval(interval);
countUp();
interval = setInterval(countUp, 200);
}
}
#Claude, you are right, the other solution I proposed was too different from original code. This is another possible solution, using setInterval and switching functions:
function onloadFunctions() {
var count = 0;
var refId = null;
var target = document.getElementById("aux");
var countUp = function() {
target.innerHTML = count;
count ++;
if(count >= 9) {
window.clearInterval(refId);
refId = window.setInterval(countDown, 500);
}
}
var countDown = function() {
target.innerHTML = count;
count --;
if(count <= 0) {
window.clearInterval(refId);
refId = window.setInterval(countUp, 500);
}
}
refId = window.setInterval(countUp, 500);
}
clearInterval(this);. You can't do that. You need to save the return value from setInterval.
var interval;
function onloadFunctions()
{
countUp();
interval = setInterval(countUp, 200);
}
var count = 0;
function countUp()
{
document.getElementById("here").innerHTML = count;
count++;
if(count == 10)
{
clearInterval(interval);
countDown();
interval = setInterval(countDown, 200);
}
}
function countDown()
{
document.getElementById("here").innerHTML = count;
count--;
if(count == 0)
{
clearInterval(interval);
countUp();
interval = setInterval(countUp, 200);
}
}
try this:
...
<body onload = "onloadFunctions();">
<script>
var cup, cdown; // intervals
var count = 0,
here = document.getElementById("here");
function onloadFunctions() {
cup = setInterval(countUp, 200);
}
function countUp() {
here.innerHTML = count;
count++;
if(count === 10) {
clearInterval(cup);
cdown = setInterval(countDown, 200);
}
}
function countDown() {
here.innerHTML = count;
count--;
if(count === 0) {
clearInterval(cdown);
cup = setInterval(countUp, 200);
}
}
</script>
From 0 - 9, up and down: <div id = "here"></div>
</body>
you could also create a single reference to #here element. Use always === instead of ==
There are many ways to solve this problem, the following is my suggestion:
function onloadFunctions() {
var count = 0;
var delta = 1;
var target = document.getElementById("here");
var step = function() {
if(count <= 0) delta = 1;
if(count >= 9) delta = -1;
count += delta;
target.innerHTML = count;
window.setTimeout(step, 500);
}
step ();
}
PS: it's safer to use setTimeout than setInteval.
/** Tools */
const log = require('ololog').configure({
locate: false
})
let count = 0
let interval__UP
let interval__DOWN
function countUp () {
count++
log.green('countUp(): ', count)
if (count == 5) {
clearInterval(interval__UP)
interval__DOWN = setInterval(function () {
countDown()
}, 1000)
}
}
function countDown () {
count--
log.red('countDown(): ', count)
if (count == 0) {
clearInterval(interval__DOWN)
interval__UP = setInterval(function () {
countUp()
}, 3000)
}
}
function start () {
countUp()
log.cyan('start()')
interval__UP = setInterval(function () {
countUp()
}, 2000)
}
start()
Console Log shows it's working