Executing multiple javascript files based on boolean conditions - javascript

I have around 5 javascript files in my WordPress website, And I tried to execute them one by one based on a boolean condition.
The javascript calls tag1.js if the count is 0.
tag2.js if the count is 1 and so on.
If the count reaches 4, the count resets to 0. And thus this is repeated continously. I tried this code. But it doesn't work even for the first time.
jQuery(document).ready(function( $ ) {
var canClick = true;
var count= 0;
$("body").click(function () {
if (canClick) {
if(parseInt(count) === 0) {
$.getScript("https:example.com/custom_js/atag1.js");
}
else if(parseInt(count) === 1) {
$.getScript("https:example.com/custom_js/atag2.js");
}
else if(parseInt(count) === 2) {
$.getScript("https:example.com/custom_js/atag3.js");
}
else if(parseInt(count) === 3) {
$.getScript("https:example.com/custom_js/atag4.js");
}
else if(parseInt(count) === 4){
$.getScript("https:example.com/custom_js/atag5.js");
count=0;
}
canClick = false;
setTimeout(() => {
canClick = true
},10000);
count = parseInt(count)+1;
}
});
});
Basically this code executes each javascript if the user clicks on the page with timeout differentiating the clicks.

If you want to load the script as per the number of clicks. Then you can look at this solution which will look more precise.
var clicks = 0;
document.addEventListener('click', () => {
loadJS();
++clicks;
});
function loadJS() {
if (clicks === 4) {
clicks = 0;
}
switch (clicks) {
case 0:
console.log('load first js');
break;
case 1:
console.log('load second js');
break;
case 2:
console.log('load 3rd js');
break;
case 3:
console.log('load 4th js');
break;
case 4:
console.log('load 5th js');
break;
default:
// code block
}
}
working demo

Related

angular 4 setinterval pausing when switch tab

My setInterval timer is pausing when leave the tab and resume when switch back to the tab I want solution to make it keep counting when the tab is switched back
here is GIF picture shows what happen
here is my code:
startCountDown(time) {
clearInterval(this.countDownInterval);
this.timeLeft = time * 100;
if (time === 0) {
return;
}
this.countDownInterval = setInterval(() => {
this.timeLeft -= 1;
if (this.timeLeft === 0) {
clearInterval(this.countDownInterval);
}
}, 10);
}
updateTimer() {
if (this.timeLeft > 0) {
$('.rolling').fadeIn(200);
$('.rolling-inner').html('<div>' + (this.timeLeft / 100).toFixed(2).replace('.', ':') + '</div>');
} else {
$('.rolling').fadeOut(200);
}
}
set timeLeft(x) {
this._timeLeft = x;
this.updateTimer();
}
get timeLeft() {
return this._timeLeft;
}
Setinterval is not misbehaving , This is what it's property . But you can track the tab selection action and add the pending idle duration with existing time.
This is the code to track the tab selection and blur
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) {
switch (e.type) {
case "blur": break;
case "focus": break;
}
}
$(this).data("prevType", e.type);
})

Javascript break/continue statement

I can't get this working:
var x = 1;
while (x == 1) {
}
function changeX(val) {
if (val == 1) {
x = 1;
} else if (val == 0) {
x = 0;
break;
}
}
and no matter what I do, I can't get this working. What I want to do is: I want the loop to stop working when I choose "0" or type it or anything. I have to use break/continue .
No matter what I do, I get wrong use of break or my browser crashes.
PS. In HTML part I put
<input type="text" value="1" onchange="changeX(this.value)">
Making your code work:
While will block the browsers thread. Therefore, you cannot click.
Do:
var x=false;
function react(){
if(x){return;}
//your code
console.log("sth");//e.g.
setTimeout(react,0);
}
react();
Now you can do your UI stuff
function changeX(val) {
if (val == 0) {
x = true;
}
}
What you really want:
var timer=false;
function input(val){
if(timer){
clearInterval(timer);
timer=false;
}
if(val){
timer=setInterval(function(){
val++;
alert(val);
if(val==10){
clearInterval(timer);
timer=false;
}
}, 1000);
}
<input oninput="input(this.value)">
<h3>Break Statement</h3>
<script>
let num=0;
while(num<5){
num++;
if((num==3)){
break;
}else{
document.write("num is: "+num+"<BR/>")
}
}
document.write("When if condition is true: while Loop Terminated");
</script>
<h3>Continue Statement</h3>
<script>
let val=0;
while(val<5){
val++;
if(val==3){
// skip the current loop iteration and jump to the next iteration
continue;
}
document.write("val = "+val+"<BR/>");
}
</script>

Showing different pictures within 0.08 seconds timeout

I have this code which is supposed to show 24 images within a 0.08333 seconds interval. However it is only showing the last image.
HTML:
<!DOCTYPE html><html><head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><script type="text/javascript" src="script.js"></script><title>page</title></head><body>
<img src="untitled.0001.jpg">
</body></html>
In javascript:
$(document).ready(function () {
$(document).keydown(function(e) {
switch(e.which) {
case 39: // right
for (var i = 1; i != 24; i++) {
setTimeout(function(){
$( "img" ).replaceWith( "<img src='image.000"+ i +".jpg'>");
},83);
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
});
How can I make it show all images within a timeout of 0.08333 seconds
Update: I tried solving it and came up with this:
$(document).ready(function () {
$(document).keydown(function(e) {
switch(e.which) {
case 39: // right
var count = 1;
while (count!=24) {
var waiting = 83 * count;
setTimeout(function() {$( "img" ).replaceWith( "<img src='avatar/walk/HumanWalk.000"+ count +".jpg'>");}, waiting);
count+=1;
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
});
Why is it still not working and showing last image only?
Use setInterval for such a case:
$(document).keydown(function(e) {
switch (e.which) {
case 39:
var c = 0;
var interval = setInterval(function() {
// set the source of your image to
// 'image.000' + (c++ -1) + '.jpg'
}, 83);
if (c === 24) clearInterval(interval);
}
});
Try this code
$(document).ready(function() {
$(document).keydown(function(e) {
switch (e.which) {
case 39: // right
for (var i = 1; i != 24; i++) {
(function(x) {
setTimeout(function() {
$("img").replaceWith("<img src='image.000" + x + ".jpg'>");
}, i*83);
})(i);
}
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
});

Why is function not executed when webpage is opened in browser?

I am trying to create a function that loops infinitely until user inputs that they would like to exit. Every time I open up the webpage in the browser, however, no prompt box appears and the infiniteLoop() function does not execute. Why is the infiniteLoop() function not being called?
function infiniteLoop() {
i= 0;
var begin= prompt("Shall we begin?");
if (begin == "Yes") {
var tryAgain= prompt("Exit loop?");
if (tryAgain != "Yes") {
infiniteLoop();
}
}
}
You need to call the function in the window onload event.
window.onload = function(){
infiniteLoop();
}
or, if you're using jquery
$(function() {
infiniteLoop();
});
The prompt box doesn't appear because you didn't call the function when your web page loads.
Add infiniteLoop() after you declare your function.
e.g.
function infiniteLoop() {
i= 0;
var begin= prompt("Shall we begin?");
if (begin == "Yes") {
while (i < 5) {
var tryAgain= prompt("Are you sure?");
if (tryAgain == "Yes") {
i++;
}
else {
infiniteLoop();
}
}
}
else {
infiniteLoop();
}
}
// Initial call
infiniteLoop();
IT WORKS, write 5 times "Yes"(case sensitive) it finishes, otherwise it works infinitely, and do not forget to call infiniteLoop()
Cleaned up and working
(function infiniteLoop() {
var begin = prompt("Shall we begin?");
if (begin === "Yes") {
var i= 0;
while (i < 5) {
var tryAgain = prompt("Are you sure?");
if (tryAgain === "Yes") {
i++;
}
else {
infiniteLoop();
}
}
}
else {
infiniteLoop();
}
})()

jQuery Memory Skill game setTimeout() issues

I am making a little game of Simon with jQuery. I have the functionality I want; start on page load, score, round numbers, etc, and the game works to an extent.
However, I still have a problem that I can't get my head around. I want to be able to prevent the user from being able to select the panels during the computer's turn. Currently, the user can trigger a sequence during the computer displaying its output, which causes havoc with buttons flashing and sounds going off.
The issue lies in setTimeout(). I tried to implement a variable 'cpuLoop' which turns to true when it's the computer's turn, and then back to false, but the implementation of setTimeout() means that there are still events on the event loop even after cpuLoop has been changed to false. The change to false changes immediately when of course it should wait until the setTimeout() has completed.
A similar problem is encountered when the reset button is clicked. When clicked, it should interrupt the setTimeout() events and restart the game. As it is, it continues outputting the computer's turn.
To get around this, I have attached the setTimeout() functions in the global scope and attempted to cut them off with clearInterval(var) but this seems to have no effect at the moment.
Here is my jQuery:
$(function(){
var counter = 0;
var cpuArray = [];
var cpuSlice = [];
var numArray = [];
var userArray = [];
var num = 1;
var wins = 0;
var losses = 0;
var cpuLoop = false;
// Initialise the game
function init(){
$('#roundNumber').html('1');
counter = 0;
cpuArray = [];
numArray = [];
userArray = [];
cpuLoop = false;
num = 1;
// Create cpuArray
function generateRandomNum(min, max){
return Math.floor(Math.random() * (max - min) + min);
}
for(var i = 1; i <= 20; i++){
numArray.push(generateRandomNum(0, 4));
}
for(var i = 0; i < numArray.length; i++){
switch(numArray[i]){
case 0:
cpuArray.push('a');
break;
case 1:
cpuArray.push('b');
break;
case 2:
cpuArray.push('c');
break;
case 3:
cpuArray.push('d');
break;
}
}
console.log('cpuArray: ' + cpuArray);
// Create a subset of the array for comparing the user's choices
cpuSlice = cpuArray.slice(0, num);
goUpToPoint(cpuSlice);
}
init();
var looperA, looperB, looperC, looperD;
// Cpu plays sounds and lights up depending on cpuArray
function cpuPlayList(input, time){
setTimeout(function(){
if(input === 'a'){
looperA = setTimeout(function(){
aSoundCpu.play();
$('#a').fadeOut(1).fadeIn(500);
}, time * 500);
} else if(input === 'b'){
looperB = setTimeout(function(){
bSoundCpu.play();
$('#b').fadeOut(1).fadeIn(500);
}, time * 500);
} else if(input === 'c'){
looperC = setTimeout(function(){
cSoundCpu.play();
$('#c').fadeOut(1).fadeIn(500);
}, time * 500);
} else if(input === 'd'){
looperD = setTimeout(function(){
dSoundCpu.play();
$('#d').fadeOut(1).fadeIn(500);
}, time * 500);
}
}, 1750);
};
// CPU takes its turn
function goUpToPoint(arr){
cpuLoop = true;
console.log('cpuLoop: ' + cpuLoop);
for(var i = 0; i < arr.length; i++){
cpuPlayList(arr[i], i);
}
cpuLoop = false;
console.log('cpuLoop: ' + cpuLoop);
}
// User presses restart button
$('.btn-warning').click(function(){
clearTimeout(looperA);
clearTimeout(looperB);
clearTimeout(looperC);
clearTimeout(looperD);
init();
});
// Array comparison helper
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].equals(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
// User presses one of the four main buttons
function buttonPress(val){
console.log('strict?: ' + $('#strict').prop('checked'));
console.log('cpuSlice: ' + cpuSlice);
userArray.push(val);
console.log('userArray: ' + userArray);
if(val === 'a'){ aSoundCpu.play(); }
if(val === 'b'){ bSoundCpu.play(); }
if(val === 'c'){ cSoundCpu.play(); }
if(val === 'd'){ dSoundCpu.play(); }
// If the user selected an incorrect option
if(val !== cpuSlice[counter])
//Strict mode off
if(!$('#strict').prop('checked')){
// Strict mode off
alert('WRONG! I\'ll show you again...');
userArray = [];
console.log('cpuSlice: ' + cpuSlice);
goUpToPoint(cpuSlice);
counter = 0;
} else {
//Strict mode on
losses++;
$('#lossCount').html(losses);
ui_alert('You lose! New Game?');
return;
} else {
// User guessed correctly
counter++;
}
if(counter === cpuSlice.length){
$('#roundNumber').html(counter + 1);
}
if(counter === 5){
ui_alert('YOU WIN!');
$('#winCount').html(++wins);
return;
}
console.log('counter: ' + counter);
if(counter === cpuSlice.length){
console.log('num: ' + num);
cpuSlice = cpuArray.slice(0, ++num);
console.log('userArray:' + userArray);
userArray = [];
console.log('cpuSlice: ' + cpuSlice);
goUpToPoint(cpuSlice);
counter = 0;
}
}
// Button presses
$('#a').mousedown(function(){
if(!cpuLoop){
buttonPress('a');
}
});
$('#b').mousedown(function(){
if(!cpuLoop) {
buttonPress('b');
}
});
$('#c').mousedown(function(){
if(!cpuLoop){
buttonPress('c');
}
});
$('#d').mousedown(function(){
if(!cpuLoop){
buttonPress('d');
}
});
// jQuery-UI alert for when the user has either won or lost
function ui_alert(output_msg) {
$("<div></div>").html(output_msg).dialog({
height: 150,
width: 240,
resizable: false,
modal: true,
position: { my: "top", at: "center", of: window },
buttons: [
{
text: "Ok",
click: function () {
$(this).dialog("close");
init();
}
}
]
});
}
// Sound links
var aSoundCpu = new Howl({
urls: ['https://s3.amazonaws.com/freecodecamp/simonSound1.mp3'],
loop: false
});
var bSoundCpu = new Howl({
urls: ['https://s3.amazonaws.com/freecodecamp/simonSound2.mp3'],
loop: false
});
var cSoundCpu = new Howl({
urls: ['https://s3.amazonaws.com/freecodecamp/simonSound3.mp3'],
loop: false
});
var dSoundCpu = new Howl({
urls: ['https://s3.amazonaws.com/freecodecamp/simonSound4.mp3'],
loop: false
});
});
and here is a link to the app on codepen. Many thanks
This seemed to work OK for me for disabling user input during the computer's turn:
function goUpToPoint(arr){
cpuLoop = true;
console.log('cpuLoop: ' + cpuLoop);
for(var i = 0; i < arr.length; i++){
cpuPlayList(arr[i], i);
}
//cpuLoop = false;
setTimeout(function() {
cpuLoop = false;
}, arr.length * 500 + 1750);
console.log('cpuLoop: ' + cpuLoop);
}
Then for the reset button, put this with your globals above function init()
timeoutsArray = [];
and make these function edits:
// Cpu plays sounds and lights up depending on cpuArray
function cpuPlayList(input, time){
timeoutsArray.push(setTimeout(function(){
if(input === 'a'){
timeoutsArray.push(setTimeout(function(){
aSoundCpu.play();
$('#a').fadeOut(1).fadeIn(500);
}, time * 500));
} else if(input === 'b'){
timeoutsArray.push(setTimeout(function(){
bSoundCpu.play();
$('#b').fadeOut(1).fadeIn(500);
}, time * 500));
} else if(input === 'c'){
timeoutsArray.push(setTimeout(function(){
cSoundCpu.play();
$('#c').fadeOut(1).fadeIn(500);
}, time * 500));
} else if(input === 'd'){
timeoutsArray.push(setTimeout(function(){
dSoundCpu.play();
$('#d').fadeOut(1).fadeIn(500);
}, time * 500));
}
}, 1750));
};
// User presses restart button
$('.btn-warning').click(function(){
for(var i = 0; i < timeoutsArray.length; i++) {
clearTimeout(timeoutsArray[i]);
}
timeoutsArray = [];
init();
});
I think you were replacing some of your looperX variable values. Using an array to store all of your setTimeout functions guarantees that they all get cleared.
Your problem is that setTimeout is an asynchronous function, which means that once you called it, the code after it continue as if it is done.
If you want the code to wait until the end of your loop, you need to invoke it at the end of the setTimeout function.
You could split your function in two (in your case it's the goUpToPoint function), something like this:
function first_part() {
//Call setTimeout
setTimeout(function() { some_function(); }, time);
}
function second_part() {
// Rest of code...
}
function some_function() {
//Delayed code...
...
second_part();
}
Since you are calling your function a number of times, I would create a global counter that you can decrease at the end of each setTimeout call, and call the second_part function only if the counter is 0:
var global_counter = 0;
function first(num) {
//Call setTimeout
global_counter = num;
for (var i = 0; i < num; i++) {
setTimeout(function() { some_function(); }, time);
}
}
function second() {
// Rest of code...
}
function some_function() {
//Delayed code...
...
// Decrease counter
global_counter--;
if (global_counter == 0) {
second();
}
}

Categories