skip timer in JavaScript interval - javascript

I currently have a function that executes some code within a setInterval method. This is working as expected. The problem is I conditionally execute code within this timer. If the condition is not met it will still wait the timeout until trying again. Is there a way of 'skipping' the delay and only executing it when the condition is met.
You will notice in my demo there is a prolonged delay between outputting paragraph results 4 and 8 (as its delaying in between the checks). I would like there to be a consistent delay throughout the whole procedure.
DEMO https://jsfiddle.net/jdec4h0x/
var intAdd = setInterval(function() {
refIndex++
if(refIndex >= predefinedMaxLimit) {
refIndex = 0;
loopedThrough = true;
}
// if this exists then increment refIndex and try again
if (loopedThrough || !$(".myclass[data-mydata1='" + predefinedData2 + "'][data-mydata2='" + refIndex + "']").length) {
counter++;
$('p').last().after('<p>IN Cond Ref = ' + refIndex + '</p>');
// ** js code within this tiemout **
if (counter >= predefinedOutputP) clearInterval(intAdd);
}
}, 500);

You can't change the delay of the interval. Either you destroy and create an interval as Kevin B said or you use setTimeout, which you have to call every time anyway, and then use a delay or another depending on a condition.
/* ... */
if (conditionIsMet) intAdd = setTimeout(function() {}, 1000);
else intAdd = setTimeout(function() {}, 1);
/* ... */
An example here

There are multjple approaches as pointed out by other users.
I would use setTimeout. I'd put this in a function that resides within a loop. You can do this with a while loop. This then gives the the ability to break out when the condition is met. you will need to increment the timer on each loop.
Fiddle https://jsfiddle.net/jdec4h0x/4/
while (progress) {
refIndex++
if (refIndex >= predefinedMaxLimit) {
refIndex = 0;
loopedThrough = true;
}
if (loopedThrough || !$(".myclass[data-mydata1='" + predefinedData2 + "'][data-mydata2='" + refIndex + "']").length) {
counter++;
myTimer = myTimer + 500;
console.log(refIndex);
myFunction(refIndex);
if (counter >= predefinedOutputP) {
$('p').last().after('<p>Cleared Interval</p>');
progress = false;
}
}
}
function myFunction(ref) {
setTimeout(function() {
$('p').last().after('<p>IN Cond Ref = ' + ref + '</p>');
// ** js code within this tiemout **
}, myTimer)
}

Related

Dom element infinitely incrementing

I'm in my first steps of creating an auto aim system for the enemy bot but I can't even seem to get him to shoot properly.
I create a div element, and move it in a direction. This happens every 4 seconds. I delete the div before the next one gets created. This works. But somehow it creates more and more elements over time and soon turns into a massive amount of divs all flying in the same direction.
** make the bullet here **
function makeBullet() {
if (player.enemy) {
if (player.enemyBullet.bulletInterval == true) {
console.log("working");
player.enemyBullet.bullet = document.createElement('div');
player.enemyBullet.bullet.className = 'bullet';
gameArea.appendChild(player.enemyBullet.bullet);
player.enemyBullet.bullet.x = player.enemy.x;
player.enemyBullet.bullet.y = player.enemy.y;
player.enemyBullet.bullet.style.left = player.enemyBullet.bullet.x + 'px';
player.enemyBullet.bullet.style.top = player.enemyBullet.bullet.y + 'px';
player.enemyBullet.bulletInterval = false;
setInterval(function () {
player.enemyBullet.bulletInterval = true;
}, 4000);
}
}
}
** Move Bullet **
function moveBullet() {
let bullets = document.querySelectorAll('.bullet');
bullets.forEach(function (item) {
item.x += 3;
item.y -= 3;
item.style.left = item.x + 'px';
item.style.top = item.y + 'px';
if(item.y < 200){
item.parentElement.removeChild(item);
player.enemyBullet.bullet = null;
}
})
}
** invoked in request Animation function **
function playGame() {
if (player.inplay) {
moveBomb();
moveBullet();
makeBullet();
window.requestAnimationFrame(playGame);
}
}
** Initiate interval boolean here **
let player = {
enemyBullet: {
bulletInterval: true
}
}
** LINK TO JS FIDDLE FULL PROJECT ** (click here to see what's happening)
https://jsfiddle.net/mugs17/j7f12a0n/
You are using setInterval like set timeout. However setInterval does not only execute one time. Once you've called setInterval the first time, calling it again makes a new different interval that also executes every 4 seconds.
So each time your function gets invoked its creating a new Interval which is why your div elements are increasing as time goes on
Instead wrap the entire create bullet code inside setInterval and make it execute only once by setting a boolean conditional and then immediately changing that conditional to false. Like this:
if (player.enemy) {
if (player.enemyBullet.bulletInterval == true) {
player.enemyBullet.bulletInterval = false;
console.log("working");
setInterval(function () {
player.enemyBullet.bullet = document.createElement('div');
player.enemyBullet.bullet.className = 'bullet';
gameArea.appendChild(player.enemyBullet.bullet);
player.enemyBullet.bullet.x = player.enemy.x;
player.enemyBullet.bullet.y = player.enemy.y;
player.enemyBullet.bullet.style.left = player.enemyBullet.bullet.x + 'px';
player.enemyBullet.bullet.style.top = player.enemyBullet.bullet.y + 'px';
}, 4000);
}
}
}

Javascript Pomodoro Timer - Pause/Play/General Functionality

so I seem to be having some real logic errors amidst my timer here, and I'm not quite sure how to fix them. I've made the code somewhat work, but I know for a fact there's a handful of logical errors, and I honestly have been working on it for a few days intermittently and can't seem to get it solved. Based on the code I've laid out you can pretty much understand my thinking of how I want to tackle this issue. I understand this isn't best practice, but I am just trying to work on my problem solving on these issues! Any help is greatly appreciated. I really need the most help on figuring out how to configure the Pause and Play functions with my given timer functionality. (Please no jQuery examples only raw JS)
// Necessary Variables for the program
let timer = document.querySelector(".time");
let button = document.querySelector("#btn");
let subtractBreak = document.querySelector("#subtractBreak");
let addBreak = document.querySelector("#addBreak");
let subtractSession = document.querySelector("#subtractSesssion");
let addSession= document.querySelector("#addSession");
// Keeping up with the current count of the break and session
let currentCount = document.getElementsByClassName("counterNum");
// Keeps up with all the buttons on session and break +/-
let counterBtn = document.getElementsByClassName("counterBtn");
// Pause and play Variables
let pause = document.querySelector("#pause");
let play = document.querySelector("#play");
// keeps up with an offsetting count.
let count = 0;
let timerGoing = false;
let sessionTimeLeft = 1500;
let breakTimeLeft = 5;
let timeWhilePaused = sessionTimeLeft;
let paused = false;
function formatTimer(time){
let minutes = Math.floor(time / 60);
let seconds = time % 60;
return `${minutes.toLocaleString(undefined, {minimumIntegerDigits: 2})}:${seconds.toLocaleString(undefined, {minimumIntegerDigits: 2})}`;
}
// This function needs to be fixed - It allows the timer to go negative past 0.
function countdown(){
timerGoing = true;
count++;
timer.innerHTML = formatTimer(sessionTimeLeft - count);
// Used to remove the listener
button.removeEventListener("click", interval);
console.log("Timer is at: " + formatTimer(sessionTimeLeft - count) + "\nCount is at: " + count + "\nsessionTimeLeft = " + sessionTimeLeft);
// Checking if the time of the current session is up
if(count == sessionTimeLeft){
timerGoing = false;
alert("We're here stop...");
startBreak(breakTimeLeft);
}
}
button.addEventListener("click", interval);
function interval(e){
setInterval(countdown, 1000);
console.log("running");
e.preventDefault();
}
/*
I look through the event listener to be sure to check and see if any of them have been hit
not just the first one, which is what it would check for.
*/
for(let i = 0; i < counterBtn.length; i++){
counterBtn[i].addEventListener("click", changeCount);
}
/*
This functions whole job is to see which button was clicked using the 'event target'
Once found it can determine if the id is subtract - then it will subtract the next element
founds' amount, due to the structure of the HTML this will always be the number following;
this process works vice versa for the addition, with the number being the element before.
*/
function changeCount(e){
let clickedButtonsId = e.target.id;
if(timerGoing == false){
if(clickedButtonsId === "subtractBreak"){
let currentValue = e.target.nextElementSibling.innerText;
if(currentValue != 1){
currentValue--;
e.target.nextElementSibling.innerText = currentValue;
breakTimeLeft -= 1;
}
} else if(clickedButtonsId === "subtractSession"){
let currentValue = e.target.nextElementSibling.innerText;
if(currentValue != 1){
currentValue--;
e.target.nextElementSibling.innerText = currentValue;
sessionTimeLeft = currentValue * 60;
// Allows the timer to update in real time
timer.innerHTML = formatTimer(sessionTimeLeft);
}
}
else if(clickedButtonsId === "addBreak"){
let currentValue = e.target.previousElementSibling.innerText;
currentValue++;
e.target.previousElementSibling.innerText = currentValue;
breakTimeLeft += 1;
}
else{
let currentValue = e.target.previousElementSibling.innerText;
currentValue++;
e.target.previousElementSibling.innerText = currentValue;
sessionTimeLeft = currentValue * 60;
// Allows the timer to update in real time
timer.innerHTML = formatTimer(sessionTimeLeft);
}
}
}
/* These functions below are not working */
pause.addEventListener("click", pauseTimer);
function pauseTimer(){
timeWhilePaused = sessionTimeLeft;
button.removeEventListener("click", interval);
console.log("calling pause"+paused+"\n");
paused = true;
console.log("paused after: " + paused);
}
play.addEventListener("click", playTimer);
function playTimer(){
console.log("Paused = " + paused);
if(paused == true){
console.log("calling play");
console.log("Paused = " + paused);
sessionTimeLeft = timeWhilePaused;
setInterval(countdown, 1000);
}
}
function startBreak(time){
console.log("Calling this function");
timer.innerHTML = formatTimer(breakTimeLeft - count);
}

Executing setTimeout() in loop takes effect only in the first iteration [duplicate]

I'm trying to make a few things scroll down the screen in javascript, however, upon execution, it just says a little and displays everything at once. So it's not clearing with the $("#Menu").html('') function and the setTimeout(function {},500) is just setting a timeout for the entire page instead of the code segment.
var MenuData = [
{'Name':'pictures','x':'30'},
{'Name':'blog','x':'50'},
{'Name':'contact','x':'42'}
]
;
var PositionArray = new Array();
$(document).ready(function () {
for (var count = 0; count < 1000; count++) {
$("#Menu").html('');
if (PositionArray[count] != null) {
PositionArray[count]++;
} else {
PositionArray[count] = 0;
}
setTimeout(function () {
for (var i in MenuData) {
$("#Menu").append('<div style="position:relative; left:' + MenuData[i].x + 'px; top:' + PositionArray[i] + 'px; ">123</div>');
}
}, 500);
}
});
Here's the fiddle: http://jsfiddle.net/LbjUP/
Edit: There was a little bit of error in the code that doesn't apply to the question. Here's the new one: http://jsfiddle.net/LbjUP/1/, I just moved PositionArray[count] to the setTimeout function as PositionArray[i]
As stated in the comments, you are creating 1000 timeouts for 500 ms at the same time - after 500 ms all of them will be executed. What you want is to increase the timeout for every scheduled function:
setTimeout(function() {
// do something
}, count * 500);
However, creating 1000 timeouts at once is not a that good idea. It would be better to use setInterval or call setTimeout "recursively" until a count of 1000 is reached, so that you only have one active timeout at a time.
var count = 0;
function update() {
// do something
if (++count < 1000)
setTimeout(update, 500);
// else everything is done
}
update();
Also, if you intend to create timeouts in a loop, be sure to be familiar with closures and their behavior when accessing counter variables after the loop ran.
Try
function recurse ( cnt ) {
for (var i in MenuData) {
$("#Menu").append('<div style="position:relative; left:' + MenuData[i].x + 'px; top:' + PositionArray[i] + 'px; ">123</div>');
}
if (cnt < 1000){
setTimeout(function () { recurse(cnt + 1); }, 500);
}
}
$("#Menu").html('');
if (PositionArray[count] != null) {
PositionArray[count]++;
} else {
PositionArray[count] = 0;
}
recurse(0);
You can also use setInterval
let i = 0;
const interval = setInterval(() => {
console.log(i);
i++;
if (i >= 10) {
clearInterval(interval);
}
}, 1000);`

Reduce setTimeout time relative to time left

I'm making a random "spinner" that loops through 8 divs and add a class active like this:
https://jsfiddle.net/9q1tf51g/
//create random setTimeout time from 3sec to 5sec
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var exit = false;
function repeat(){
//my code
if(!exit){
setTimeout(repeat, 50);
}
}
My problem is, I want the function repeat to end slowly, to create more suspense. I think I can do this by raising the 50 from the timeout but how can I do this accordingly to the time left?
Thanks in advance!
You can try this.
$('button').on('click', function(){
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var anCounter = 1;
var anState = "positive";
var exit = false;
//var time1 = 50000;
setInterval(function(){time = time-1000;}, 1000);
function repeat(){
if(anCounter>7 && anState=="positive"){ anState="negative"}
if(anCounter<2 && anState=="negative"){ anState="positive"}
$('div[data-id="'+anCounter+'"]').addClass('active');
$('div').not('div[data-id="'+anCounter+'"]').removeClass('active');
if(anState=="positive"){anCounter++;}else{anCounter--;}
if(!exit){
if(time <1000)
setTimeout(repeat, 300);
else if(time< 2000)
setTimeout(repeat, 100);
else setTimeout(repeat, 50);
}
}
repeat();
setTimeout(function(){
exit=true;
},time);
});
Once you know that you need to exit the flow (exit is true ) you can trigger some animation by creating a dorm linear serials of you code. Usually this animation should not last more than 2 sec.
You were kind of on the right track but it'd be easier to check the time you've passed by and increment accordingly at a fixed rate. I set it to increase by 50ms every iteration but you could change that to whatever you like.
Fiddle Demo
Javascript
$('button').on('click', function() {
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var anCounter = 1;
var anState = "positive";
var elapsed = 0;
var timer;
function repeat(timeAdded) {
if (anCounter > 7 && anState == "positive") {
anState = "negative"
}
if (anCounter < 2 && anState == "negative") {
anState = "positive"
}
$('div[data-id="' + anCounter + '"]').addClass('active');
$('div').not('div[data-id="' + anCounter + '"]').removeClass('active');
if (anState == "positive") {
anCounter++;
} else {
anCounter--;
}
if (elapsed < time) {
timer = setTimeout(function() {
repeat(timeAdded + 50);
}, timeAdded);
elapsed += timeAdded;
}
else {
clearTimeout(timer);
}
}
repeat(0);
});
You can add a parameter called intTime to your function repeat and inside that function you can adjust the next timeout and call the repeat function with the new timeout. each time it gets called it will take 20 ms longer. however you adjust the increment by changing the 20 in
var slowDown=20; to a different number.
var slowDown=20;
setTimeout ("repeat",50);
function repeat(intTime){
//my code
if(!exit){
intTime=Math.floor (intTime)+slowDown;
setTimeout(repeat(intTime), intTime);
}
}
And then you will need to create another timeout for the exit.
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var exit = false;
setTimeout ("stopSpinning",time);
function stopSpinning(){
exit = true;
}
so the whole thing should look something like this
var slowDown=20;
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var exit = false;
setTimeout ("stopSpinning",time);
setTimeout ("repeat",50);
function repeat(intTime){
//my code
if(!exit){
intTime=Math.floor (intTime)+20;
setTimeout(repeat(intTime), intTime);
}
}
function stopSpinning(){
exit = true;
}
Fiddle Demo
Linear deceleration: //values are just an example:
add a var slowDown = 0; inside the click event handler
add slowDown += 1; inside the repeat function
pass 50+slowDown to setTimeout
Curved deceleration:
add a var slowDown = 1;and a var curveIndex = 1.05 + Math.random() * (0.2); // [1.05-1.25)inside the click event handler
add slowDown *= curveIndex; inside the repeat function
pass 50+slowDown to setTimeout

Image animation with speed control

We have some problem with our image animation with speed control.
It make use of a timeout to change the image, but we want to change the timeout value with a slider, but for some sort of reason, it doesn't work. Can someone help us out ?
We have a Jfiddle here: http://jsfiddle.net/Kbroeren/fmd4xbew/
Thanks! Kevin
var jArray = ["http://www.parijsalacarte.nl/images/mickey-mouse.jpg", "http://www.startpagina.nl/athene/dochters/cliparts-disney/images/donad%20duck-106.jpg", "http://images2.proud2bme.nl/hsfile_203909.jpg"];
var image_count = 0;
function rollover(image_id, millisecs) {
var image = document.getElementById(image_id);
image.src = jArray[image_count];
image_count++;
if (image_count >= jArray.length) {
image_count = 0;
}
var timeout = setTimeout("rollover('" + image_id + "'," + millisecs + ");", millisecs);
}
rollover("img1", 200);
$(function () {
var value;
var $document = $(document),
$inputRange = $('input[type="range"]');
// Example functionality to demonstrate a value feedback
function valueOutput(element) {
var value = element.value,
output = element.parentNode.getElementsByTagName('output')[0];
output.innerHTML = value;
}
for (var i = $inputRange.length - 1; i >= 0; i--) {
valueOutput($inputRange[i]);
};
$document.on('change', 'input[type="range"]', function (e) {
valueOutput(e.target);
rollover("img1", 200);
});
// end
$inputRange.rangeslider({
polyfill: false
});
});
You keep creating more and more infinite function calls without stopping them.
After you call your function the first time, it keeps calling itself.
then you call it again with different interval (millisecs) and it will also start call itself....
You can try two different approach.
1.Use setInterval instead of setTimeout. Use clearInterval to clear the interval before setting it with a new value.
/// Call animation() every 200 ms
var timer = setInterval("Animation()",200);
function ChageSpeed(miliseces){
///Stop calling Animation()
clearInterval(timer);
/// Start calling Animation() every "miliseces" ms
timer = setInterval("Animation()",miliseces);
}
function Animation(){
/// Animation code goes here
}
2.Or, Instead, Set your interval as a global variable (not cool) and just change it value when the user want to change the animation speed.
var millisecs = 200;
function rollover(image_id) {
var image = document.getElementById(image_id);
image.src = jArray[image_count];
image_count++;
if (image_count >= jArray.length) {
image_count = 0;
}
var timeout = setTimeout("rollover('" + image_id + "'," + millisecs + ");", millisecs);
}
$document.on('change', 'input[type="range"]', function (e) {
valueOutput(e.target);
millisecs = YourNewValue;
});

Categories

Resources