I want to make images in assets called Leo + a number appearing and disappearing but it change images when the image is shown the half of the time, I don't understand why, i tried changing milliseconds but nothing
var counterForImages = 0
let leo = $("#Leo")
var photoAppearing = window.setInterval(function(){
var fadingIn = window.setInterval(function(){
leo.css("opacity", Number(leo.css("opacity"))+0.02)
if (leo.css("opacity") == 1) {
clearInterval(fadingIn)
}
}, 25)
var fadingOut = window.setInterval(function(){
leo.css("opacity", Number(leo.css("opacity"))-0.02)
if (leo.css("opacity") == 0) {
clearInterval(fadingOut)
}
}, 25)
leo.attr("src", "assets/Leo" + counterForImages%3 + ".png")
if (counterForImages%3 == 0) {
leo.css("width", "200px")
leo.css("left", "85%")
} else if (counterForImages%3 == 1) {
leo.css("width", "400px")
leo.css("left", "80%")
} else if (counterForImages%3 == 2) {
leo.css("width", "180px")
leo.css("left", "85%")
}
counterForImages++
}, 5000);
UPDATE
tried the following, does someone know how to avoid maximum recursion depth and do something forever?
var counterForImages = 1
let leo = $("#Leo")
async function delay(ms) {
// return await for better async stack trace support in case of errors.
return await new Promise(resolve => setTimeout(resolve, ms));
}
async function lol (fun) {
var fadingIn = window.setInterval(function(){
leo.css("opacity", Number(leo.css("opacity"))+0.02)
if (leo.css("opacity") == 1) {
clearInterval(fadingIn)
}
}, 50)
await delay(5000)
var fadingOut = window.setInterval(function(){
leo.css("opacity", Number(leo.css("opacity"))-0.02)
if (leo.css("opacity") == 0) {
clearInterval(fadingOut)
}
}, 50)
await delay(5000)
leo.attr("src", "assets/Leo" + counterForImages%3 + ".png")
if (counterForImages%3 == 0) {
leo.css("width", "200px")
leo.css("left", "85%")
} else if (counterForImages%3 == 1) {
leo.css("width", "400px")
leo.css("left", "80%")
} else if (counterForImages%3 == 2) {
leo.css("width", "180px")
leo.css("left", "85%")
}
counterForImages++
fun(lol)
}
lol(lol)
it looks like you are using jQuery, not pure JavaScript.
If I understand what you're doing, this might work:
var image_data=[[200,85], [400,80], [180,85]];
var counterForImages=0, leo=$('#leo');
function rotateImage() {
counterForImages=counterForImages%3;
leo.css({
opacity:0,
width:image_data[counterForImages][0]+'px',
left:image_data[counterForImage][1]+'%'
});
leo.attr('src', 'assets/Leo' + counterForImages + '.png');
leo.animate({opacity:1}, 5000, ()=>{
leo.animate({opacity:0}, 5000, ()=>{
counterForImages++;
rotateImage();
});
})
}
Related
I have a perfectly working script. Basically, I am polling an API every 5 seconds for myJson.Temperature and a MIDI note is played corresponding to the returned value. The values are between 0 and 16. Here is the script:
let easymidi = require("easymidi")
let output = new easymidi.Output("mindiPort", true)
let interval;
const fetch = require("node-fetch");
let sendNote = (noteValue, duration) => {
output.send("noteon", noteValue)
setTimeout(()=> {
output.send("noteoff", noteValue)
}, duration);
}
const api_url = 'https://www.placeholder_url.com?timeout=1000'
setInterval(() =>
fetch(api_url)
.then((response) => {
return response.json();
})
.then((myJson) => {
let note;
if (myJson.temperature == 0) {
note = 24;
} else if (myJson.temperature == 2) {
note = 25;
} else if (myJson.temperature == 4) {
note = 26;
} else if (myJson.temperature == 6) {
note = 27;
} else if (myJson.temperature == 8) {
note = 28;
} else if (myJson.temperature == 10) {
note = 29;
} else if (myJson.temparature == 12) {
note = 30;
} else if (myJson.temperature == 14) {
note = 31;
} else {
note = 32;
}
let noteValue = {
note: note,
velocity: 100,
channel: 1
}
sendNote(noteValue, 500)
}), 5000); // API call every 5 seconds **This will also play a (same) note every five seconds
// if conditions are met**
How do can I get the note to only play once ie; - if a subsequent poll is done and returns the same value, that note can be ignored until a unique value is returned? I have looked at filter and onlyUnique but I am not sure how to incorporate them into the code. Thank You in advance.
I would go for a simple approach and keep track of last emited note:
EDIT: my code was wrong because it was checking against complex objects equality, fixed it
let easymidi = require("easymidi")
let output = new easymidi.Output("mindiPort", true)
let interval;
const fetch = require("node-fetch");
let lastNote = null;
let sendNote = (noteValue, duration) => {
output.send("noteon", noteValue)
setTimeout(()=> {
output.send("noteoff", noteValue)
}, duration);
}
const api_url = 'https://www.placeholder_url.com?timeout=1000'
setInterval(() =>
fetch(api_url)
.then((response) => {
return response.json();
})
.then((myJson) => {
let note;
if (myJson.temperature == 0) {
note = 24;
} else if (myJson.temperature == 2) {
note = 25;
} else if (myJson.temperature == 4) {
note = 26;
} else if (myJson.temperature == 6) {
note = 27;
} else if (myJson.temperature == 8) {
note = 28;
} else if (myJson.temperature == 10) {
note = 29;
} else if (myJson.temparature == 12) {
note = 30;
} else if (myJson.temperature == 14) {
note = 31;
} else {
note = 32;
}
if (lastNote !== note) {
let noteValue = {
note: note,
velocity: 100,
channel: 1
}
sendNote(noteValue, 500)
}
lastNote = note;
}), 5000); // API call every 5 seconds **This will also play a (same) note every five seconds
// if conditions are met**
This all seems to work, but the button (bSaveNewTag) never becomes enabled. Going through it, I am guessing that countTag is not populated in time, but I don't get how to make it wait for a return value.
I have gone through with alerts which has made come to the above conclusion, but my knowledge of Javascript is very basic, so don't know what to do and when searching for answers, what I do find, I don't understand and can't figure out how to implement.
function checkIfNewTagExists(potentialTag) {
var countTag = 0;
$.ajax({
url: "/CSC/api/checkTag/" + potentialTag + "/",
dataType: "json",
success: function (data) {
$.map(data, function (item) {
countTag = parseInt(item.cTag, 10);
});
},
complete: function () {
if (countTag > 0) {
$('#newTag').css({ 'opacity': 1 });
$('#tbNewTagName').addClass("missing");
} else {
$('#newTag').css({ 'opacity': 0 });
}
return countTag;
}
});
}
function checkNewTag() {
var countTag = 0;
var potentialTag = '';
var val = Page_ClientValidate("vgNewTag");
var el = $("#bSaveNewTag")
for (i = 0; i < Page_Validators.length; i++) {
if (Page_Validators[i].isvalid) {
$("#" + Page_Validators[i].controltovalidate).removeClass("missing");
} else {
$("#" + Page_Validators[i].controltovalidate).addClass("missing");
}
}
potentialTag = $('#tbNewTagName').val();
if (potentialTag == '') {
countTag = 1;
} else {
countTag = checkIfNewTagExists(potentialTag);
}
if (val && countTag === 0) {
el.prop("disabled", false);
} else {
el.prop("disabled", true);
return false;
}
}
If you did not understand my comments above, or the article I referenced, here is the breakdown of what you should do.
function checkIfNewTagExists(potentialTag, callback) {
var countTag = 0;
$.ajax({
url: "/CSC/api/checkTag/" + potentialTag + "/",
dataType: "json",
success: function (data) {
$.map(data, function (item) {
countTag = parseInt(item.cTag, 10);
});
},
complete: function () {
if (countTag > 0) {
$('#newTag').css({ 'opacity': 1 });
$('#tbNewTagName').addClass("missing");
} else {
$('#newTag').css({ 'opacity': 0 });
}
//return countTag;
callback(countTag);
}
});
}
Then this part:
potentialTag = $('#tbNewTagName').val();
if (potentialTag == '') {
countTag = 1;
} else {
countTag = checkIfNewTagExists(potentialTag);
}
if (val && countTag === 0) {
el.prop("disabled", false);
} else {
el.prop("disabled", true);
return false;
}
Should be (something) like this:
potentialTag = $('#tbNewTagName').val();
if (potentialTag == '') {
countTag = 1;
el.prop("disabled", true);
} else {
//countTag = checkIfNewTagExists(potentialTag);
checkIfNewTagExists(function(cTag){
countTag = cTag;
if (val && countTag === 0) {
el.prop("disabled", false);
} else {
el.prop("disabled", true);
}
});
}
Now, I can see you have the return false; in the last else line of checkNewTag. If you intend to return something to the calling line, you should also use a callback function instead of var x = checkNewTag();
There is an object.
There is this method that initializes the timer in another method within the same object.
initstep1() {
var totAns = TriviaGame.corAnswered + TriviaGame.incorAnswered;
//for (let v=0;v<TriviaGame.arrayOfSelected.length;v++){TriviaGame.arrayOfSelected.pop();}
//for (let u=0;u<TriviaGame.arrayOfIntervals.length;u++){clearInterval(TriviaGame.arrayOfIntervals[u]);TriviaGame.arrayOfIntervals.pop();}
$("#maincontact0").css("display", "none");
$("#maincontact2").css("display", "none");
$("#maincontact1").css("display", "flex");
if (totAns != 10) {
TriviaGame.populatePromptContent();
} else {
TriviaGame.initstep3();
}
if (TriviaGame.corAnswered == 0 && TriviaGame.incorAnswered == 0) {
TriviaGame.giveQuestionsClickEvents();
TriviaGame.giveAnswersClickEvents();
}
$("#maincontact1qr").text() == 30;
TriviaGame.timerOnTheRight();
}
It's called timerOnTheRight...
Here it is...
Never gets cleared no matter what I do.
timerOnTheRight() {
//for (let u=0;u<TriviaGame.arrayOfIntervals.length;u++){clearInterval(TriviaGame.arrayOfIntervals[u]);TriviaGame.arrayOfIntervals.pop();}
console.log(TriviaGame.arrayOfIntervals);
let countDown1 = 30;
var thisVeryTimer = setInterval(function() {
countDown1--;
if ($("#maincontact1qr").text() != 1) {
$("#maincontact1qr").text(countDown1);
}
if ($("#maincontact1qr").text() < 11) {
$("#maincontact1qr").css("color", "orange");
}
if ($("#maincontact1qr").text() < 4) {
$("#maincontact1qr").css("color", "red");
}
if ($("#maincontact1qr").text() == 1) {
TriviaGame.arrayOfCurrent[0].timespent = "Yes";
clearInterval(thisVeryTimer);
TriviaGame.initstep2();
}
}, 600);
}
Make sure the conditional is correct, and the inside the conditional block is working when conditioning is met. You should console out thisVeryTimer to make sure it is the same interval id.
Another issue should be the scope of the variable.
clearInterval(thisVeryTimer);
Try to move the above code out of the interval block.
I have a small javascript animation that shows a new dropdown select menu after the previous one has been chosen.
Heres the HTML:
<div class="steps">
<div id="step1">
<button type="button" class="button standardBtn" style="opacity: 1.5" id="toJapanese" onclick="setToJapanese(); activatePullDown()">To Japanese</button>
<button type="button" class="button standardBtn" style="opacity: 1.5" id="toWestern" onclick="setToWestern(); activatePullDown()">To Western</button>
</div>
<div id="step2" style="opacity: 0"></div>
<div id="step3" style="opacity: 0"></div>
<div id="step4" style="opacity: 0"></div>
</div>
When a button from step1 is clicked, the first menu, step2, appears. When an item from step2 is selected, it moves to the left and a new menu, step3, shows. It works in every browser except IE (10 and 11). In IE, step2 moves over correctly, but step3 fails to show.
Heres my Javascript for when step2 is selected.
function yearSelected() {
startMoveLeft('step3');
getMonths();
setTimeout(fadeIn, 600, 'step3', 'normal', 0);
}
function startMoveLeft(id) {
var element = document.getElementById(id);
var mq = window.matchMedia( "(min-width: 800px)" );
var display = [];
if (mq.matches) {
display = 'inline-block';
}
else {
display = 'block';
}
element.style.display = display;
element.style.visibility = 'visible';
element.style.width = '0px';
doMoveLeft(element);
}
function doMoveLeft(element) {
console.log(element.style.width);
if (parseInt(element.style.width, 10) < convertEmToPx(8)) {
var width = parseInt(element.style.width) + 4 + 'px';
element.style.width = width;
setTimeout(function() {
doMoveLeft(element);
}, 1);
}
}
function getMonths() {
var xmlhttp = createXmlhttp();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('toJapanese').className += ' activeButton';
document.getElementById('toWestern').className += ' unactiveButton';
document.getElementById('step3').innerHTML = xmlhttp.responseText;
}
};
var year = document.getElementById("yearSelect").value;
var token = document.getElementsByTagName('input').item(name = "_token").value;
var data = "_token=" + token + "&year=" + year;
xmlhttp.open("POST", "ajax/getMonths", true);
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
function fadeIn(id, time, fade) {
var element = document.getElementById(id);
if (element.style.opacity < 1) {
FX.fadeIn(element, {
duration: setDuration(time)
}, fade);
}
}
function setDuration(time) {
if (time === 'very_fast') {
return 200;
}
else if (time === 'fast') {
return 400;
}
else if (time === 'normal') {
return 600;
}
else if (time === 'slow') {
return 800;
}
else if (time === 'very_slow') {
return 1000;
}
else {
return 0;
}
}
(function() {
var FX = {
easing: {
linear: function(progress) {
return progress;
},
quadratic: function(progress) {
return Math.pow(progress, 2);
},
swing: function(progress) {
return 0.5 - Math.cos(progress * Math.PI) / 2;
},
circ: function(progress) {
return 1 - Math.sin(Math.acos(progress));
},
back: function(progress, x) {
return Math.pow(progress, 2) * ((x + 1) * progress - x);
},
bounce: function(progress) {
for (var a = 0, b = 1, result; 1; a += b, b /= 2) {
if (progress >= (7 - 4 * a) / 11) {
return -Math.pow((11 - 6 * a - 11 * progress) / 4, 2) + Math.pow(b, 2);
}
return 0;
}
},
elastic: function(progress, x) {
return Math.pow(2, 10 * (progress - 1)) * Math.cos(20 * Math.PI * x / 3 * progress);
}
},
animate: function(options) {
var start = new Date();
var id = setInterval(function() {
var timePassed = new Date() - start;
var progress = timePassed / options.duration;
if (progress > 1) {
progress = 1;
}
options.progress = progress;
var delta = options.delta(progress);
options.step(delta);
if (progress == 1) {
clearInterval(id);
options.complete;
}
}, options.delay || 10);
},
fadeOut: function(element, options, to) {
if (to === undefined) {
to = 1;
}
this.animate({
duration: options.duration,
delta: function(progress) {
progress = this.progress;
return FX.easing.swing(progress);
},
complete: options.complete,
step: function(delta) {
element.style.opacity = to - delta;
}
});
},
fadeIn: function(element, options, to) {
if (to === undefined) {
to = 0;
}
if (element.style.opacity === 0) {
to = 0;
}
this.animate({
duration: options.duration,
delta: function(progress) {
progress = this.progress;
return FX.easing.swing(progress);
},
complete: options.complete,
step: function(delta) {
element.style.opacity = to + delta;
}
});
}
};
window.FX = FX;
})();
Ive tested these functions all individually and they work fine, but together something is not right. Id really appreciate some insight.
UPDATE: It has something to do with the AJAX request. Its not picking up the _token value. This line seems to be causing the problem:
document.getElementsByTagName('input').item(name = "_token").value;
The item function of HTMLCollection takes an integer argument (an index), not a CSS selector (you can't pass a selector like that, anyway). You probably meant to say this:
var token = document.querySelector("input[name='_token']").value;
So, This is my first Windows 8 app and I'm working on it using html/css and JS
I've developped it on a browser at first (I know, not a good habit) and I wanted to try it out on the Windows 8.1 app
Everything seemed to have slight glitches that I easily fixed, yet the javascript code didn't work at all, even though it worked perfectly on the browser.
Short story: the app enables you to make a countdown from 1h down, or 10mn down (for some purpose), it has two bottuns for each countdown: a start and a stop button.
I have no idea why, the cosole shows the following error: HTML1701
Here's the code:
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
args.setPromise(WinJS.UI.processAll());
}
};
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. You might use the
// WinJS.Application.sessionState object, which is automatically
// saved and restored across suspension. If you need to complete an
// asynchronous operation before your application is suspended, call
// args.setPromise().
$(document).ready(function () {
var h, m, s, h1, m1, s1, output, output1, inter, inter1;
//Preparing all the functions
//facts' animation function
function facts() {
function solve() {
setTimeout(function () {
$("#fun1").animate({ opacity: "0", }, 500, function () {
$("#fun2").animate({ opacity: "1" }, 500);
});
}, 10500);
setTimeout(function () {
$("#fun2").animate({ opacity: "0", }, 500, function () {
$("#fun3").animate({ opacity: "1" }, 500);
});
}, 21500);
setTimeout(function () {
$("#fun3").animate({ opacity: "0", }, 500, function () {
$("#fun4").animate({ opacity: "1" }, 500);
});
}, 31500);
setTimeout(function () {
$("#fun4").animate({ opacity: "0", }, 500, function () {
$("#fun1").animate({ opacity: "1" }, 500);
});
}, 41500);
}
solve();
setInterval(function () { solve(); }, 41520);
//Work Counting functions
}
function startWork() {
h = 1;
m = 0;
s = 0;
document.getElementById("WTM").innerHTML = "01:00:00"
inter = setInterval(function () { countWork() }, 1000);
}
function countWork() {
if (s == 0 && m == 0 && h == 0) {
$("#StartW").animate({ opacity: 1, }, 500);
clearInterval(inter);
}
else if (s == 0 && m == 0 && h != 0) {
h = h - 1;
m = 59;
s = 59;
}
else if (s == 0 && m != 0) {
m = m - 1;
s = 59;
}
else if (s != 0)
{ s = s - 1; }
if (typeof (s) != "string" && s < 10)
{ s = "0" + s; }
if (typeof (m) != "string" && m < 10)
{ m = "0" + m; }
if (typeof (h) != "string" && h < 10)
{ h = "0" + h; }
output = h + ":" + m + ":" + s;
document.getElementById("WTM").innerHTML = output;
}
//Rest Counting functions
function startRest() {
h1 = 0;
m1 = 10;
s1 = 0;
document.getElementById("RTM").innerHTML = "00:10:00";
inter1 = setInterval(function () { countRest() }, 1000);
}
function countRest() {
if (s1 == 0 && m1 == 0 && h1 == 0) {
$("#StartR").animate({ opacity: 1, }, 500);
clearInterval(inter1);
}
else if (s1 == 0 && m1 == 0 && h1 != 0) {
h1 = h1 - 1;
m1 = 59;
s1 = 59;
}
else if (s1 == 0 && m1 != 0) {
m1 = m1 - 1;
s1 = 59;
}
else if (s1 != 0)
{ s1 = s1 - 1; }
if (typeof (s1) != "string" && s1 < 10)
{ s1 = "0" + s1; }
if (typeof (m1) != "string" && m1 < 10)
{ m1 = "0" + m1; }
if (typeof (h1) != "string" && h1 < 10)
{ h1 = "0" + h1; }
output1 = h1 + ":" + m1 + ":" + s1;
document.getElementById("RTM").innerHTML = output1;
}
//Calling the needed functions
$("#StopW").click(function () {
clearInterval(inter);
document.getElementById("WTM").innerHTML = "00:00:00";
$("#StartW").animate({ opacity: 1, }, 500);
});
$("#StartW").click(function () {
startWork();
$("#StartW").animate({ opacity: 0, }, 2000);
});
$("#StopR").click(function () {
clearInterval(inter1);
document.getElementById("RTM").innerHTML = "00:00:00";
$("#StartR").animate({ opacity: 1, }, 500);
});
$("#StartR").click(function () {
startRest();
$("#StartR").animate({ opacity: 0, }, 2000);
});
facts();
});
};
app.start();
})();
It appears you're using jQuery. Make sure you're using jQuery 2.0 and serving it locally from your app package.
The specific error you're seeing is likely the result of using innerHTML to set the countdown timers. Because apps run with elevated privileges (potential access to user files, etc), your code must not do things that may introduce vulnerabilities. innerHTML can be used to dynamically load scripts and thus it's use is discouraged.
In your application it looks like you could easily use innerText instead. If you must use innerHTML, try using toStaticHTML() or wrapping it in MSApp.execUnsafeLocalFunction(). You can read more about developing secure apps.
don't use the VS2013 Previews any longer. The RTM is already out. Get the final Version here:
http://www.microsoft.com/visualstudio/eng/downloads#d-2013-express