Converting async es6 syntax function to es5 syntax async function - javascript

I'm working with a package where I'm converting the function definitions of that package (https://github.com/3DJakob/react-tinder-card/blob/master/index.js) back to es5 syntax, however, I'm not being able to convert the animateOut function since it is an async function:
const animateOut = async (element, speed, easeIn = false) => {
const startPos = getTranslate(element)
const bodySize = getElementSize(document.body)
const diagonal = pythagoras(bodySize.x, bodySize.y)
const velocity = pythagoras(speed.x, speed.y)
const time = diagonal / velocity
const multiplier = diagonal / velocity
const translateString = translationString(speed.x * multiplier + startPos.x, -speed.y * multiplier + startPos.y)
let rotateString = ''
const rotationPower = 200
if (easeIn) {
element.style.transition = 'ease ' + time + 's'
} else {
element.style.transition = 'ease-out ' + time + 's'
}
if (getRotation(element) === 0) {
rotateString = rotationString((Math.random() - 0.5) * rotationPower)
} else if (getRotation(element) > 0) {
rotateString = rotationString((Math.random()) * rotationPower / 2 + getRotation(element))
} else {
rotateString = rotationString((Math.random() - 1) * rotationPower / 2 + getRotation(element))
}
element.style.transform = translateString + rotateString
await sleep(time * 1000)
}
Can someone help me? Thanks!

Essentially you'll need to expand any awaits to a promise, and make sure that the animateOut is also treated with .then() as opposed to await:
var animateOut = function(element, speed, easeIn) {
easeIn = easeIn || false;
// animateOut code here
return sleep(1000).then(function() {
console.log('Already slept, done.')
})
}
animateOut().then(function() {
console.log('Done animating out')
})
function sleep(time) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve();
}, time)
})
}
jsfiddle

Related

Waiting for a promise to resolve from a loop

I have an app that animates a value. Below, if to is set, the amount lerps to it.
const lerp = (v0, v1, t) => {
return (1 - t) * v0 + t * v1;
}
const app = {
to: false,
amount: 20,
animate(){
requestAnimationFrame(this.animate.bind(this));
if(this.to !== false){
this.amount = lerp(this.amount, this.to, 0.1)
if(Math.abs(this.amount - this.to) < 0.001){
this.amount = this.to;
this.to = false;
}
console.log(this.amount);
}
},
init(){
this.animate();
}
}
app.init();
console.log("Waiting to start");
setTimeout(() => {
console.log("Started!");
app.to = 0;
}, 1000)
This works great. But I'd like to call a function when it finishes the process, and that function may change. Ideally, I'd like to add it like so:
...
promise: null,
animate(){
requestAnimationFrame(this.animate.bind(this));
if(this.to !== false){
this.amount = lerp(this.amount, this.to, 0.1)
if(Math.abs(this.amount - this.to) < 0.001){
this.amount = this.to;
this.to = false;
// Resolve the promise so logic can continue elsewhere
if(this.promise) this.promise.resolve();
}
}
console.log(this.amount);
},
stop(){
this.promise = something... // Not sure what this should be
await this.promise;
// subsequent logic
nextFunction()
}
I can't get my head around how I can properly set this up. Any help welcome.
Wrapper entire function in promise and then resolve it
const lerp = (v0, v1, t) => {
return (1 - t) * v0 + t * v1;
}
const app = {
to: false,
amount: 20,
animate() {
return new Promise(resolve => {
const inner = () => {
requestAnimationFrame(inner.bind(this));
if (this.to !== false) {
this.amount = lerp(this.amount, this.to, 0.1)
if (Math.abs(this.amount - this.to) < 0.001) {
this.amount = this.to;
this.to = false;
resolve()
}
}
console.log(this.amount);
}
inner()
})
},
init() {
return this.animate();
}
}
app.init().then(() => alert('over'));
setTimeout(() => {
app.to = 0;
}, 1000)
In order to create a promise for an arbitrary action (rather than a promise for the whole animate loop like Konrad showed) I used something from this answer: https://stackoverflow.com/a/53373813/630203 to create a promise I could resolve from anywhere.
const createPromise = () => {
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
};
const lerp = (v0, v1, t) => {
return (1 - t) * v0 + t * v1;
}
const app = {
to: false,
amount: 20,
animateToPromise: null,
animateToResolve: null,
animate(){
requestAnimationFrame(this.animate.bind(this));
if(this.to !== false){
this.amount = lerp(this.amount, this.to, 0.1)
if(Math.abs(this.amount - this.to) < 0.001){
this.amount = this.to;
this.to = false;
if(this.animateToPromise){
this.animateToResolve();
this.animateToPromise = null;
this.animateToResolve = null;
}
}
console.log(this.amount);
}
},
init(){
this.animate();
},
async animateTo(n){
const { promise: animateToPromise, resolve: animateToResolve } =
createPromise();
this.to = n;
this.animateToPromise = animateToPromise;
this.animateToResolve = animateToResolve;
await this.animateToPromise;
return true;
}
}
app.init();
console.log("Waiting to start");
(async () => {
setTimeout(async () => {
console.log("Started!");
await app.animateTo(0);
console.log("Got to 0!");
console.log("now for 20");
await app.animateTo(20);
console.log("done :)");
}, 1000)
})();
This means I can queue my promises with a single animate function running.

Script tag unsuccessful

This works broken apart in js fiddle but when using a script tag the clock no longer works (no longer calls js). I have tried text/javascript , adding the javascript version in a script above and my latest attempt was adding language.
How do i determine how a line of javascript is suppose to be used in a script tag? Is there any way to figure out what phrase is suppose to be used in order for this to work.
It was originally made on code pen and it shows the javascript version is 1.7 there but i cannot get this to work if i use a script tag for the life of me.
<script language="JavaScript">/**[minimum JS only to set current time and sound the chimes]**/
(function () {
"use strict";
let seconds = document.getElementById("second_time"),
munutes = document.getElementById("minute_time"),
hours = document.getElementById("hour_time"),
s,
m,
h,
S,
M,
H,
time;
/*[set the clock to correct time and let CSS handle the rest]*/
function windup() {
(time = new Date()),
(s = time.getSeconds()),
(m = time.getMinutes()),
(h = time.getHours()),
(S = s * 6),
(M = m * 6 + s / 10),
(H = h * 30 + 0.5 * m);
seconds.style.transform = "rotate(" + S + "deg)";
munutes.style.transform = "rotate(" + M + "deg)";
hours.style.transform = "rotate(" + H + "deg)";
console.log("windup: " + h + ":" + m + ":" + s);
tick.volume = chime.volume = 1;
}
setTimeout(windup, 0);
/*[main visibility API function]*/
// use visibility API to check if current tab is active or not
let vis = (function () {
let stateKey,
eventKey,
keys = {
hidden: "visibilitychange",
webkitHidden: "webkitvisibilitychange",
mozHidden: "mozvisibilitychange",
msHidden: "msvisibilitychange"
};
for (stateKey in keys) {
if (stateKey in document) {
eventKey = keys[stateKey];
break;
}
}
return function (c) {
if (c) document.addEventListener(eventKey, c);
return !document[stateKey];
};
})();
/*[HTML5 Visibility API]****************************************/
// check if current tab is active or not
vis(function () {
if (vis()) {
setTimeout(function () {
// tween resume() code goes here
windup();
console.log("tab is visible - has focus");
}, 300);
} else {
// tween pause() code goes here
console.log("tab is invisible - has blur");
tick.volume = chime.volume = 0.1;
}
});
// check if browser window has focus
let notIE = document.documentMode === undefined,
isChromium = window.chrome;
if (notIE && !isChromium) {
// checks for Firefox and other NON IE Chrome versions
$(window)
.on("focusin", function () {
// tween resume() code goes here
setTimeout(function () {
windup();
console.log("focus");
}, 300);
})
.on("focusout", function () {
// tween pause() code goes here
console.log("blur");
tick.volume = chime.volume = 0.1;
});
} else {
// checks for IE and Chromium versions
if (window.addEventListener) {
// bind focus event
window.addEventListener(
"focus",
function (event) {
// tween resume() code goes here
setTimeout(function () {
windup();
console.log("focus");
}, 300);
},
false
);
// bind blur event
window.addEventListener(
"blur",
function (event) {
// tween pause() code goes here
console.log("blur");
tick.volume = chime.volume = 0.1;
},
false
);
} else {
// bind focus event
window.attachEvent("focus", function (event) {
// tween resume() code goes here
setTimeout(function () {
windup();
console.log("focus");
}, 300);
});
// bind focus event
window.attachEvent("blur", function (event) {
// tween pause() code goes here
console.log("blur");
tick.volume = chime.volume = 0.1;
});
}
}
/*[end HTML5 Visibility API]************************************/
/*[hourly and quarterly chimes]*/
const tick = document.getElementById("tick");
const chime = document.getElementById("chime");
const sound_dir = "http://www.gerasimenko.com/sandbox/codepen/sounds/";
let bell,
tock = "tock.wav";
tick.src = sound_dir + tock;
function hourly_chime(n) {
console.log("plays left: " + n);
if (n === 0) {
return;
} else {
chime.pause();
chime.currentTime = 0;
chime.play();
n--;
setTimeout(function () {
hourly_chime(n);
}, 3000);
}
}
setInterval(function () {
(time = new Date()),
(s = time.getSeconds()),
(m = time.getMinutes()),
(h = time.getHours());
console.log("watch: " + h + ":" + m + ":" + s);
tick.play();
if (s === 0 && (m === 15 || m === 30 || m === 45)) {
bell = "ding-tone.wav";
chime.src = sound_dir + bell;
hourly_chime(m / 15);
} else if (s === 0 && m === 0) {
bell = "bell-japanese.wav";
chime.src = sound_dir + bell;
h > 12 ? (h = h - 12) : h;
hourly_chime(h);
}
}, 1000);
})();
</script>

In stuck mode to try and create a loop for my products in HTML

I have nearly finished with my project but now stuck on the hardest challenge - create a loop. I am not sure maybe map is the right method to do this. Basically, I have created a 3D can that rotates clockwise that shows the user of the can in full detail. When the cursor hovers the can, the can doubles the size and displays in front of the screen, again to see it in much better detail. Because there are different colour cans for different types of flavours, I need to create a loop and avoid DRY. However, I am struggling to do this.
I am not asking for someone to do this for me but someone to say look at these methods or try this out and see if it works differently etc…
https://codepen.io/Rosstopherrr/pen/GVRvxJ
This is my code. Hopefully, when you look at it you understand what I am. I have a 3D can on display, in an active slider but the next number of slides are empty. This is where I want to fill in the gaps for different cans - that will slide to the left, and if the cursor hovers the can it will display front of the screen.
Just really asking for advice on what to do next, what problems I should be looking at, etc. I’ve been struggling for a week now trying to create a loop but finding it impossible
$("#products>article").on("click", function(){
$("#products>article").removeClass("active");
$(this).addClass("active");
animate();
});
function getActiveArticle(){
var x = 0;
$("#products>article").each(function(e){
if($("#products>article").eq(e).hasClass("active")){
x = e;
return false;
}
});
return x;
}
function gofwd(){
var activeIndex = getActiveArticle();
var minArticles = 0;
var maxArticles = $("#products>article").length - 1;
if(activeIndex >= maxArticles){
activeIndex = minArticles-1;
}
$("#products>article").removeClass("active");
$("#products>article").eq(activeIndex+1).addClass("active");
animate();
}
function gobwd(){
var activeIndex = getActiveArticle();
var minArticles = 1;
var maxArticles = $("#products>article").length;
$("#products>article").removeClass("active");
$("#products>article").eq(activeIndex-1).addClass("active");
animate();
}
$(document).ready(function(){
animate();
});
function animate(){
var articleIndex = getActiveArticle();
var totalMargin = 25 * (articleIndex+1) - (25*(articleIndex));
var articlePosition = Math.floor($("#products>article").eq(articleIndex).offset().left - $("#products").offset().left) - totalMargin;
var productsHalfWidth = $("#products").width()/2;
if(articleIndex == 0){
var halfWidth = 150;
}else{
var halfWidth = 100;
}
var finalPosition = productsHalfWidth - articlePosition - halfWidth;
$("#products").animate({
"left": finalPosition,
}, {
duration: 500,
easing: 'easeOutBack',
});
}
$(window).on("resize", function(){
animate();
});
var autoPlay = setInterval(function(){
gofwd();
}, 3500);
$("#slider").on("mouseenter", function(){
clearInterval(autoPlay);
});
$("#slider").on("mouseleave", function(){
autoPlay = setInterval(function(){
gofwd();
}, 4500);
});
const getElement = (selector) => document.querySelector(selector);
const createElement = (tag) => document.createElement(tag);
// const addBackground1 = document.style['background'] = 'url ("https://i.postimg.cc/BZ8rj2NM/sleve.png")';
const addSideStyle = ($side, i) => {
let deg = 3.75 * i;
let bgPosition = 972 - (i * 10.125);
$side.style['background-position'] = bgPosition + 'px 0';
$side.style['-webkit-transform'] = 'rotateY(' + deg + 'deg) translateZ(154px)';
$side.style['-moz-transform'] = 'rotateY(' + deg + 'deg) translateZ(154px)';
$side.style['transform'] = 'rotateY(' + deg + 'deg) translateZ(154px)';
};
const createBottle = () => {
const $bottle = createElement('div');
$bottle.classList.add('bottle');
const $bottleLabel = createBottleLabel();
for (let i = 0; i < 96; i = i + 1){
let $bottleSide = createBottleSide(i);
$bottleLabel.append($bottleSide);
}
$bottle.append($bottleLabel);
return $bottle;
};
const createBottleLabel = () => {
const $bottleLabel = createElement('div');
$bottleLabel.classList.add('label');
return $bottleLabel;
}
const createBottleSide = (i) => {
const $bottleSide = createElement('div');
$bottleSide.classList.add('side');
addSideStyle($bottleSide, i);
return $bottleSide;
};
const changeBottleSize = (clickFn) => {
const _bottle = createElement('div');
_bottle.classList.add('bottle');
_bottle.style['transform'] = 'scale(0.9)';
return _bottle;
}
const moveBottle = (moveFn) => {
const _moveBottle = createElement('div');
_moveBottle.classList.add('bottle');
_moveBottle.style['left'] = "-1000px";
return _moveBottle;
}
const clickFn = () => {
const $bottleSize = getElement('.container');
const $bottle1 = changeBottleSize();
const $bottle2 = changeBottleSize();
const $bottle3 = changeBottleSize();
$bottleSize.style['transform'] = 'scale(0.9)';
return $bottleSize;
}
const moveFn = () => {
const $bottleMove = getElement('.container');
const $move1 = moveBottle();
$bottleMove.style['left'] = "-1000px";
return $bottleMove;
}
const initApp = () => {
const $container = getElement('.container');
const $bottle1 = createBottle();
const $bottle2 = createBottle();
const $bottle3 = createBottle();
[$bottle1, $bottle2, $bottle3].forEach(($bottle, i) => {
$bottle.classList.add('bottle' + i);
});
$container.append($bottle1, $bottle2, $bottle3);
};
initApp();

Use GraphicsMagic with generator function and yield

I'm generating a watermark in a png image with GraphicsMagic in NodeJs and then I want to upload to Aws S3 server, I have 2 functions the first to create the watermark in the picture
function * createWatermark(watermark, text) {
const textWidth = pixelWidth(text, { size: 37 });
return gm('public/watermark/' + watermark)
.size(function (err, size) {
if (!err) {
const width = size.width;
const height = size.height;
const marginBottom = 30;
const marginRight = 60;
//create first pattern
return gm('public/watermark/' + watermark)
.font("public/fonts/sofia/2E827A_2_0.ttf", 37)
.fill('rgba(255,255,255, 0.8)')
.drawText((width-textWidth-marginRight), (height-marginBottom), text)
.write('public/img/temp/' + watermark, function(e){
// console.log('done', e); // What would you like to do here?
return e;
});
}
});
}
the second function is to upload to picture to AWS S3 server
function * uploadCreatedWatermark(fiileName, author, withPattern, format){
var pathFile = 'public/img/temp/' + fiileName;
var watermarkReadStream = fs.createReadStream(pathFile);
yield AWSService.uploadFormFileStreamToAWS(
Env.get('AWS_WATERMARK_FOLDER') + '/' + format,
author + (withPattern ? '_pattern' : '')+'.png',
watermarkReadStream,
{isRootPath: true}
);
}
the second function was created 1 month ago for another developer, I only created the first function (to create the watermark in the png file).
From the main function I call both
class ExampleController {
* foo(request, response) {
var text = 'aaron | gallereplay';
var author = 'aaron';
var watermark = 'Cinemagraph_watermarks_1_1.png';
yield createWatermark(watermark, text);
yield uploadCreatedWatermark(watermark, author, false, '1_1');
}
}
but it fails, because the first function is running before the second one ends and the png file does not yet exist
Extra Info:
1) My first Idea was put the second function into the first one, but that fail because the function doesn't exist
function * createWatermark(watermark, text) {
const textWidth = pixelWidth(text, { size: 37 });
return gm('public/watermark/' + watermark)
.size(function (err, size) {
if (!err) {
const width = size.width;
const height = size.height;
const marginBottom = 30;
const marginRight = 60;
//create first pattern
return gm('public/watermark/' + watermark)
.font("public/fonts/sofia/2E827A_2_0.ttf", 37)
.fill('rgba(255,255,255, 0.8)')
.drawText((width-textWidth-marginRight), (height-marginBottom), text)
.write('public/img/temp/' + watermark, function(e){
// console.log('done', e); // What would you like to do here?
// return e;
yield uploadCreatedWatermark(watermark, 'author', true, '1_1');
});
}
});
}
2) both functions createWatermark and uploadCreatedWatermark is out of the class
class ExampleController() {
* foo(request, response) { ... }
}
function * createWatermark() { ... }
function * uploadCreatedWatermark() { ... }
PD: Sorry about my english, My main lenguage is Spanish

How to get my function to increase variable "_time"

// videogame.js
// don't forget to validate at jslint.com
/*jslint devel: true, browser: true */
/*global $*/
$(function () {
"use strict";
// global functions
function boundaryCheck(element_selector) {
var element = $(element_selector);
var universe = $("#universe");
var p = element.position();
if (p.left < 0) {
element.css("left", "0px");
}
if (p.top < 0) {
element.css("top", "0px");
}
if (p.left + element.width() > universe.width()) {
element.css("left", (universe.width() - element.width()) + "px");
}
if (p.top + element.height() > universe.height()) {
element.css("top", (universe.height() - element.height()) + "px");
}
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
// Constructor for Player Ship object
function PlayerShip() {
var my = {};
$("#universe").append($("<div>").attr("id", "player"));
my.navigate = function (keys) {
var RIGHTARROW_KEYCODE = 39;
var LEFTARROW_KEYCODE = 37;
var UPARROW_KEYCODE = 38;
var DOWNARROW_KEYCODE = 40;
if (keys === RIGHTARROW_KEYCODE) {
$("#player").css("left", "+=10px");
}
if (keys === LEFTARROW_KEYCODE) {
$("#player").css("left", "-=10px");
}
if (keys === UPARROW_KEYCODE) {
$("#player").css("top", "-=10px");
}
if (keys === DOWNARROW_KEYCODE) {
$("#player").css("top", "+=10px");
}
boundaryCheck("#player");
};
return my;
}
// Constructor for Enemy Ship object
function EnemyShip() {
var my = {};
$("#universe").append($("<div>").attr("id", "enemy"));
my.move = function (paused) {
if (!paused) {
var left = Boolean(getRandomInt(0, 2));
var top = Boolean(getRandomInt(0, 2));
if (left) {
$("#enemy").css("left", "-=" + getRandomInt(1, 10) + "px");
} else {
$("#enemy").css("left", "+=" + getRandomInt(1, 10) + "px");
}
if (top) {
$("#enemy").css("top", "-=" + getRandomInt(1, 10) + "px");
} else {
$("#enemy").css("top", "+=" + getRandomInt(1, 10) + "px");
}
boundaryCheck("#enemy");
}
};
return my;
}
// this might make an asteroid happen, maybe. I don't know if it will work.
function Asteroid() {
var my = {};
$("#universe").append($("<div>").attr("id", "asteroid"));
my.move = function (paused) {
if (!paused) {
var left = Boolean(getRandomInt(0, 2));
var top = Boolean(getRandomInt(0, 2));
if (left) {
$("#asteroid").css("left", "-=" + getRandomInt(1, 10) + "px");
} else {
$("#asteroid").css("left", "+=" + getRandomInt(1, 10) + "px");
}
if (top) {
$("#asteroid").css("top", "-=" + getRandomInt(1, 10) + "px");
} else {
$("#asteroid").css("top", "+=" + getRandomInt(1, 10) + "px");
}
boundaryCheck("#asteroid");
}
};
return my;
}
// Constructor for Game object
function Game() {
// total points
var _health = 1000;
var _time = 0;
// is the game paused?
var _game_paused = false;
// speed of background animation in ms (larger = slower)
var _background_speed = 100;
// player ship
var _player_ship = new PlayerShip();
// enemy ship
var _enemy_ship = new EnemyShip();
var _asteroid = new Asteroid(); //make this an actual thing
var my = {
health: _health,
time: _time,
game_paused: _game_paused,
background_speed: _background_speed,
player_ship: _player_ship,
enemy_ship: _enemy_ship,
asteroid: _asteroid
};
$("#universe").append($("<div>").attr("id", "results"));
$("#results").append($("<h1>"));
$("#universe").append($("<div>").attr("id", "results2"));
$("#results2").append($("<h1>"));
my.health = function (value) {
if (value === undefined) {
return _health;
}
_health = value;
return my;
};
my.time = function (value) {
if (value === undefined) {
return _time;
}
_time = value;
return my;
};
my.game_paused = function (value) {
if (value === undefined) {
return _game_paused;
}
_game_paused = value;
return my;
};
my.background_speed = function (value) {
if (value === undefined) {
return _background_speed;
}
_background_speed = value;
return my;
};
my.player_ship = function (value) {
if (value === undefined) {
return _player_ship;
}
_player_ship = value;
return my;
};
function runtimer() {
_time++;
};
my.enemy_ship = function (value) {
if (value === undefined) {
return _enemy_ship;
}
_enemy_ship = value;
return my;
};
my.asteroid = function (value) {
if (value === undefined) {
return _asteroid;
}
_asteroid = value;
return my;
};
// METHODS
// display total points
my.displayHealth = function () {
$("#results h1").html("Health: " + _health);
};
my.increaseTime = function () {
setInterval(function(){ runTimer() }, 1000)
}
my.displayTimer = function () {
$("#results2 h1").html("Time: "+ _time);
};
my.moveBackground = function () {
if (!_game_paused) {
var background_position = $("#universe")
.css("backgroundPosition")
.split(" ");
var current_x = parseInt(background_position[0], 10);
var current_y = parseInt(background_position[1], 10);
var new_x = current_x - 1;
var new_y = current_y;
$("#universe").css({
"background-position": new_x + "px " + new_y + "px"
});
}
};
my.checkKeys = function () {
var ESCAPE_KEYCODE = 27;
$(document).keydown(function (key_event) {
if (key_event.which === ESCAPE_KEYCODE) {
if (_game_paused) {
_game_paused = false;
$("#pause").remove();
} else {
_game_paused = true;
var pause = $("<div>", {id: "pause"});
$("body").prepend(pause);
}
} else {
_player_ship.navigate(key_event.which);
}
});
};
my.checkCollisions = function (paused) {
var p = $("#player");
var e = $("#enemy");
var ppos = p.position();
var epos = e.position();
if (!paused) {
if (
(
(ppos.left + p.width() < epos.left) ||
(ppos.left > epos.left + e.width())
) ||
(
(ppos.top + p.height() < epos.top) ||
(ppos.top > epos.top + e.height())
)
) {
return false;
} else {
return true;
}
}
};
my.checkAsteroid = function (paused) {
var p = $("#player");
var a = $("#asteroid");
var ppos = p.position();
var apos = a.position();
if (!paused) {
if (
(
(ppos.left + p.width() < apos.left) ||
(ppos.left > apos.left + a.width())
) ||
(
(ppos.top + p.height() < apos.top) ||
(ppos.top > apos.top + a.height())
)
) {
return false;
} else {
return true;
}
}
};
my.play = function () {
_enemy_ship.move(_game_paused);
_asteroid.move(_game_paused);
if (my.checkCollisions(_game_paused)) {
_health --;
my.displayHealth();
} else if (
my.checkAsteroid(_game_paused)) {
_health --;
my.displayHealth();
}
};
return my;
}
var game = new Game();
game.checkKeys();
game.displayHealth();
game.displayTimer();
game.increaseTime();
setInterval(game.moveBackground, game.background_speed);
setInterval(game.play, game.background_speed);
});
I'm relatively new to programming. I took a class in high school, which was very mediocre. I'm now taking some starter courses in college, and my assignment is to improve a generic space game (which I have already started doing). I have a div for the timer, but for some reason, I can't get any functions to increase the _time variable. It's almost as though they're not allowed to access it. I have a function called "runTimer", which is supposed to increase "_time" by one every time it is run. I have another function called "increaseTime", which is supposed to run "runTimer" every 1000 milliseconds. The variable never seems to increase though. This hasn't been my first spaghetti code implementation of a timer, since I've tried various things over the past few hours. I just can't understand why the variable won't increase.
This is a big hunk of code. As RobG pointed out, try to work on paring back your question to the minimal, complete, and verifiable example you can.
That said, at a glance, it would appear that your timer probably is updating. At least _time is.
The problem is likely you are never re-drawing your div, so it isn't showing the updated value. You need to call game.displayTimer() every time _time updates.
Probably the easiest place to add it would be in your setInterval() in increaseTime():
my.increaseTime = function () {
setInterval(function(){
runTimer();
my.displayTime();
}, 1000)
}

Categories

Resources