how to trigger the increment only once - javascript

I have used the setTimeout function so my object stays on y<0 for a while and at that time i want to my increment to trigger only once but it keeps on triggering ...more i delay my function using the setTimeout function higher times the increment operation gets trigger......so what is the solution through which my increment triggers only once no matter how long my object stays in y<0
Player.prototype.checkInWater = function () {
if (this.y < 0) {
++scoreGot
setTimeout(function(){
player.x = 202;
nplayer.y = 405;
}, 300);
}
};

Player = function(){
....
this.checkedInWater = false;
}
Player.prototype.checkInWater = function () {
if (this.y < 0 && !this.checkedInWater) {
++scoreGot;
t = this;
t.checkedInWater = true;
setTimeout(function(){
player.x = 202;
nplayer.y = 405;
t.checkedInWater = false;
}, 300);
}
};

Related

Setting interval only once by an event listener, but run other functions every time

See this code:
function handleTouchStart(event) {
event.preventDefault();
cnvs.removeEventListener("touchstart", handleTouchStart);
var x1 = event.touches[0].clientX-cnvs.offsetLeft;
callerOfCNVSTouchStart = setInterval(function () {
if (x1 > cnvs.width/2 && whiteShip.x2 < cnvs.width) {
whiteShip.x1+= 3;
} else if (x1 < cnvs.width/2 && whiteShip.x1 > 0) {
whiteShip.x1-= 3;
}
}, 20);
nBMC = setInterval(makeNewBullets,200);
setInterval(sendEnemies,2000);//I want to run this line only once
}
I want the other functions to run every time the event occurs, but set the interval for sendEnemies only once. How can I do that?
Use a variable like var sentEnemies = false; outside function handleTouchStart and update it in the function to true the first time and use if(!sentEnemies) for the line to execute only once.
var sentEnemies = false;
function handleTouchStart(event) {
event.preventDefault();
cnvs.removeEventListener("touchstart", handleTouchStart);
var x1 = event.touches[0].clientX-cnvs.offsetLeft;
callerOfCNVSTouchStart = setInterval(function () {
if (x1 > cnvs.width/2 && whiteShip.x2 < cnvs.width) {
whiteShip.x1+= 3;
} else if (x1 < cnvs.width/2 && whiteShip.x1 > 0) {
whiteShip.x1-= 3;
}
}, 20);
nBMC = setInterval(makeNewBullets,200);
if (!sentEnemies) {
setInterval(sendEnemies,2000); // Will execute only once
sentEnemies = true;
}
}

Adding timeout to a loop

I have a function that will perform an action when the timer reaches 5000ms:
var timer = new Timer(function () {
console.log("refreshingBid");
refreshBid();
}, 5000);
timer.pause();
if (isElementInViewport() === true) {
console.log("element in view");
timer.resume();
} else {
timer.pause();
console.log("element is out of view")
}
//I am trying to loop this 5 times with the 5000ms delay - the code I am using for this is:
for (i=0;i<=5;i++)
{
MyFunc();
}
It seems regardless of whether I put the for loop in the timer or whether I put the timer inside the for loop the result is the same where all 5 loops happen instantaneously instead of with a delay of the timer being applied? I'm not sure what i'm doing wrong here... Any help would be appreciated!
Sorry, edit to include the complete code below:
<script>
var iframe2 = document.getElementById('postbid_if');
function isElementInViewport() {
var el = document.getElementById('postbid_if')
console.log(el)
var rect = el.getBoundingClientRect();
console.log(rect)
return rect.bottom >= 0 &&
rect.right >= 0 &&
rect.left < (window.innerWidth || document.documentElement.clientWidth) &&
rect.top < (window.innerHeight || document.documentElement.clientHeight);
}
function Timer(callback, delay) {
var timerId, start, remaining = delay;
this.pause = function () {
window.clearTimeout(timerId);
remaining -= new Date() - start;
};
this.resume = function () {
start = new Date();
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining);
};
this.resume();
}
for (i = 0; i <= 5; i++) {
MyFunc();
}
var timer = new Timer(function () {
console.log("refreshingBid");
refreshBid();
}, 5000);
timer.pause();
if (isElementInViewport() === true) {
console.log("element in view");
timer.resume();
} else {
timer.pause();
console.log("element is out of view")
}
</script>
It's because it's looping through quickly 5 times then all 5 loops are delaying after the 5 seconds. The timeout pauses it after 5 seconds, not for 5 seconds up front.
Perhaps you could revise your code in this way to achieve the timer based iterations as required:
//Track the current iteration
var i = 0;
function MyFunc() {
var timer = new Timer(function () {
console.log("refreshingBid");
refreshBid();
// The current timer has completed. If the current
// iteration is less than 5...
if(i < 5) {
i++;
// .. then start another timer for the next iteration
MyFunc();
}
}, 5000);
timer.pause();
if (isElementInViewport() === true) {
console.log("element in view");
timer.resume();
} else {
timer.pause();
console.log("element is out of view")
}
}
// Start the first iteration
MyFunc();

Making a timer with code that can easily be reset

I'm making a shot clock for my school's basketball team. A shot clock is a timer that counts down from 24 seconds. I have the skeleton for the timer right now, but I need to have particular key bindings. The key bindings should allow me to rest, pause, and play the timer.
var count=24;
var counter=setInterval(timer, 1000);
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " secs";
}
I'm not sure what you meant by "rest" the timer, I interpret this as "pause", so:
Space = Pause / Play.
R = Reset.
var
count=24,
counter = setInterval(timer, 1000),
running = true;
function timer() {
count -= 1;
if (count <= 0) {
clearInterval(counter);
}
document.getElementById("timer").innerHTML = count + " secs";
}
window.addEventListener("keydown", function(e) {
switch(e.keyCode) {
case 32: // PLAY
running ? clearInterval(counter) : counter = setInterval(timer, 1000);
running = !running;
break;
case 82: // RESET
clearInterval(counter);
document.getElementById("timer").innerHTML = 24 + " secs";
count = 24;
running = false;
}
});
<div id="timer">24 secs</div>
I am not able to comment yet, but I recommend checking out this post Binding arrow keys in JS/jQuery
The linked post explains how to bind arrow keys using js/jquery. Using http://keycode.info/ you can find out the keycodes of your desired keys and replace the current values then continue to build your code from there.
Here is my code sample: http://codepen.io/anon/pen/vLvWJM
$(document).ready(function() {
var $timer = $('#timer');
var $timerStatus = $('#timerStatus');
var timerValue = 24;
var intervalId = null;
var timerStatus = 'stopped';
if(!$timer.length) {
throw 'This timer is missing a <div> element.';
}
$(document).keydown(function(k) {
if(k.which == 80) {
if(timerStatus === 'playing') {
clearInterval(intervalId);
timerStatus = 'stopped';
updateTimerStatus();
return;
}
intervalId = setInterval(function() {
playTimer();
timerStatus = 'playing';
updateTimerStatus();
}, 1000);
} else if(k.which == 82) {
clearInterval(intervalId);
resetTimer();
updateText();
timerStatus = 'stopped';
updateTimerStatus();
}
});
function playTimer() {
if(timerValue > 0) {
timerValue--;
updateText();
}
}
function resetTimer() {
timerValue = 24;
}
function updateText() {
$timer.html(timerValue);
}
function updateTimerStatus() {
$timerStatus.html(timerStatus);
}
});
<div id="timerStatus">stopped</div>
<div id="timer">24</div>

Restart setInterval each minute

To create a ticking movement and not a sliding one of a number on a canvas i want to move the number up in 0,2 secondes and wait 0,8 seconds. The codes works good for a sliding movement but to implement the ticking i get lost.
jsfiddle
var ittt = 0;
var add = null;
function MinuteTimer() {
add = setInterval(function () {
totime();
if (ittt % (40 * 60) == 0) {
ittt = 0;
}
}, 5);
};
function stoptimer() {
clearInterval(add);
};
function totime() {
drawcanvasbackground();
drawnumberscanvas(ittt);
ittt += 1;
if (ittt % 40 == 0 && ittt > 0) {
clearInterval(add);
setTimeout(MinuteTimer(), 800);
};
};

JavaScript to delay execution of functions after page is loaded

I wrote this javascript to make an animation. It is working fine in the home page. I wrote a alert message in the last.
If I go other then home page, this alert message has to come, but I am getting alert message, if I remove the function, alert message working on all pages, any thing wrong in my code?
window.onload = function(){
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
var signUp = document.getElementById('signup-link');
if (yellows != 'undefined' && signUp != undefined){
function animeYellowBar(num){
setTimeout(function(){
yellows[num].style.left = "0";
if(num == yellows.length-1){
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},num*250);
}
}, num * 500);
}
for (var i = 0; i < yellows.length; i++){
animeYellowBar(i);
}
}
alert('hi');
}
DEMO: http://jsbin.com/enaqu5/2
var yellows,signUp;
window.onload = function() {
yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
signUp = document.getElementById('signup-link');
if (yellows !== undefined && signUp !== undefined) {
for (var i = 0; i < yellows.length; i++) {
animeYellowBar(i);
}
}
alert('hi')
}
function animeYellowBar(num) {
setTimeout(function() {
yellows[num].style.left = "0";
if (num == yellows.length - 1) {
setTimeout(function() {
signUp.style.webkitTransform = "scale(1)";
},
num * 250);
}
},
num * 500);
}
DEMO 2: http://jsbin.com/utixi4 (just for sake)
$(function() {
$("#magazine-brief h2").each(function(i,item) {
$(this).delay(i+'00').animate({'marginLeft': 0 }, 500 ,function(){
if ( i === ( $('#magazine-brief h2').length - 1 ) )
$('#signup-link')[0].style.webkitTransform = "rotate(-2deg)";
});
});
});
For starters you are not clearing your SetTimeout and what are you truly after here? You have 2 anonymous methods that one triggers after half a second and the other triggers a quarter of a second later.
So this is just 2 delayed function calls with horribly broken syntax.
Edited Two possibilities, one fixes your current code... the latter shows you how to do it using JQuery which I would recomend:
var yellows, signUp;
window.onload = function(){
yellows = document.getElementById('magazine-brief');
if(yellows != null){
yellows = yellows.getElementsByTagName('h2');
}else{
yellows = null;
}
signUp = document.getElementById('signup-link');
if (yellows != null && signUp != null && yellows.length > 0)
{
for(var i = 0; i < yellows.length; i++)
{
animeYellowBar(i);
}
}
alert('hi');
}
function animeYellowBar(num)
{
setTimeout(function(){
yellows[num].style.left = "0";
if(num == yellows.length-1){
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},num*250);
}
}, num * 500);
}
The below approach is a SUMMARY of how to use JQuery, if you want to use JQuery I'll actually test it out:
//Or using JQuery
//Onload equivelent
$(function(){
var iterCount = 0,
maxIter = $("#magazine-brief").filter("h2").length;
$("#magazine-brief").filter("h2").each(function(){
setTimeout(function(){
$(this).css({left: 0});
if(iterCount == (maxIter-1))
{
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},iterCount*250);
}
}, iterCount++ * num );
});
});

Categories