How to setInterval() and removeInterval() in this situation? - javascript

I understand that in order to remove an interval you need a stored reference to it, so I figured I'll store function returns in a global array.
But why when I click on a cell the intervals keep going and only one stops (I saw first and last cell to stop flashing)?
What I wanted it to do is append a continuous fadeTo on all cells of a table row (excluding first one), and a listener that on clicking any of these cells would stop animations on all of them.
Here's my best effort so far (jsfiddle):
var intervals;
var target = $('#table');
var qty = target.find('td:contains(Price)');
var row = qty.closest('tr');
arr = new Array();
row.find('td').each( function() {
if ($(this).text() !== "Price" ) {
intervals = new Array();
addAnimation($(this));
}
});
function addAnimation(cell) {
var intv = setInterval(function() {
cell.fadeTo("slow", 0.3);
cell.fadeTo("slow", 1);
}, 1000);
intervals.push(intv);
cell.click(function() {
for (var i = 0; i < intervals.length; intervals++) {
window.clearInterval(intervals[i]);
}
});
}

You are instantiating the intervals array multiple times and incrementing the wrong parameter in the for loop:
var intervals = [],
target = $('#table'),
qty = target.find('td:contains(Price)'),
row = qty.closest('tr');
row.find('td').each( function() {
if ($(this).text() !== "Price" ) {
addAnimation($(this));
}
});
function addAnimation(cell) {
var intv = setInterval(function() {
cell.fadeTo("slow", 0.3);
cell.fadeTo("slow", 1);
}, 1000);
intervals.push(intv);
cell.click(function() {
for (var i = 0; i < intervals.length; i++) {
window.clearInterval(intervals[i]);
}
$(this).stop();
});
}
See: fiddle

Your other problem is here:
var intervals;
...
if ($(this).text() !== "Price" ) {
intervals = new Array();
addAnimation($(this));
That creates a new array each time. You should be initialising intervals when you declare it and delete the line creating a new array in the if block:
var intervals = [];
...
if ($(this).text() !== "Price" ) {
addAnimation($(this));
}
However, you may wish to run this more than once, so you should clear out the array when you clear the intervals, something like:
function addAnimation(cell) {
var intv = setInterval(function() {
cell.fadeTo("slow", 0.3);
cell.fadeTo("slow", 1);
}, 1000);
intervals.push(intv);
cell.click(function() {
for (var i = 0; i < intervals.length; intervals++) {
window.clearInterval(intervals[i]);
}
// reset the array
intervals = [];
});
}
or replace the for loop with something like:
while (intervals.length) {
window.clearInterval(intervals.pop());
}
which stops the intervals and clears the array in one go. :-)

Related

Clar Ajax data after each OnClick and then append new data

I'm doing a project for school. A memory game that uses the pokéAPI to get images.
I have three buttons depending on the game level (easy, medium, hard) and it generates the amount of cards.
When I click a button it generates the pictures but when I click it again it append the new data into the same selector.
I have tried with: $('#output').html(''), $('#output').append(''), $('#output').remove(), $('#output').empty()
// Settings for game level. Each integer represents number of cards * 2.
let easy = 4;
let medium = 6;
let hard = 8;
// Arrays for PokemonImgUrl.
let originalPokemonImgUrl = [];
let duplicateAllPokemonImgUrl = [];
let allPokemonImgUrl = [];
// PokéAPI URL.
const pokemonDataUrl = 'https://pokeapi.co/api/v2/pokemon/';
// This function creates a random number depending on the settings below.
function randomNumber() {
// Settings for max randomnumbers starting from index 1.
let randomNumberMax = 500;
let fromIndex = 1;
// Math random function with values from randomnumbers.
return Math.floor(Math.random() * randomNumberMax) + fromIndex;
}
// Function for getting data from PokéAPI.
function getData() {
$.ajax ({
type: 'GET',
url: pokemonDataUrl + randomNumber(), // Calling randomnnumber to get a random pokémon.
success: function(pokemonData) {
var pokemonImgUrl = pokemonData.sprites.front_default; // Store and extract pokemon images.
originalPokemonImgUrl.push(pokemonImgUrl); // store ImagesURL to a global array called allPokemonImgUrl.
}
})
}
// Shuffle code from css-tricks.com.
function Shuffle(cards) {
for(var j, x, i = cards.length; i; j = parseInt(Math.random() * i), x = cards[--i], cards[i] = cards[j], cards[j] = x);
return cards;
};
// function iterates through allPokemonImgUrl array and outputs it into the DOM.
function output() {
allPokemonImgUrl.forEach(function (i) {
$('#output').append('<img src="'+ [i] +'">');
}
)}
/* This function copies the array so that we always have two of the same cards.
Then concat into a new array and shuffles it. After that it outputs the result.*/
function startGame(){
setTimeout( function(){
duplicateAllPokemonImgUrl = originalPokemonImgUrl.slice();
}, 1000 );
setTimeout( function(){
allPokemonImgUrl = originalPokemonImgUrl.concat(duplicateAllPokemonImgUrl);
}, 1500 );
setTimeout( function(){
Shuffle(allPokemonImgUrl)
}, 2000 );
setTimeout( function(){
output();
}, 2500 );
}
/* Events for clicking on game levels. It iterates to check how many cards it needs
and calls the function getData accordingly. */
$(document).on('click', '#easy', function() {
for (var cards = 0; cards < easy; cards++) {
getData();
}
startGame();
})
$(document).on('click', '#medium', function() {
for (var cards = 0; cards < medium; cards++) {
getData();
}
startGame();
})
$(document).on('click', '#hard', function() {
for (var cards = 0; cards < hard; cards++) {
getData();
}
startGame();
})
When I click a button I get the images as expected.
But when I click it again it appends the new data after the old data. I want to remove the old ajax data first and then append the new data.
I found the solution:
Adding a clear function:
function clear() {
originalPokemonImgUrl = [];
duplicateAllPokemonImgUrl = [];
allPokemonImgUrl = [];
$('#output').empty();
}
Then just call it:
$(document).on('click', '#easy', function() {
for (var cards = 0; cards < easy; cards++) {
getData();
}
clear();
startGame();
})

Update live JavaScript Array while pushing elements to HTML ID

I am facing a slight dilemma as a JavaScript newbie. Let me explain the script:
I have implemented a JavaScript function rss() which pulls from an internet RSS news feed and saves the news headlines into an array newsArray[].
The function headlinesInsert() should push every item in the array to the HTML ID #headlineInsert, similarly to how it is shown here.
However, the linked example's textlist variable (which should be replaced with my local newsArray[]) does not seem to be 'compatible' for some reason as when replacing nothing shows on the HTML side.
The idea is that the rss() function updates the global newsArray[] with new headlines every 10 minutes while the headlinesInsert() pushes this data to the HTML ID constantly (as per the linked example).
With my limited knowledge of JavaScript, I am hoping someone could help me set the following code right and put the idea into action.
// Push RSS Headlines into HTML ID
var newsArray = [];
var listTicker = function headlinesInsert(options) {
var defaults = {
list: [],
startIndex:0,
interval: 8 * 1000,
}
var options = $.extend(defaults, options);
var listTickerInner = function headlinesInsert(index) {
if (options.list.length == 0) return;
if (!index || index < 0 || index > options.list.length) index = 0;
var value = options.list[index];
options.trickerPanel.fadeOut(function headlinesInsert() {
$(this).html(value).fadeIn();
});
var nextIndex = (index + 1) % options.list.length;
setTimeout(function headlinesInsert() {
listTickerInner(nextIndex);
}, options.interval);
};
listTickerInner(options.startIndex);
}
// The following line should hold the values of newsArray[]
var textlist = new Array("News Headline 1", "News Headline 2", "News Headline 3", "News Headline 4");
$(function headlinesInsert() {
listTicker({
list: textlist ,
startIndex:0,
trickerPanel: $('#headlineInsert'),
interval: 8 * 1000,
});
});
$(function slow(){
// Parse News Headlines into array
function rss() {
$.getJSON("https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.stuff.co.nz%2Frss", function(data) {
newsArray = [];
for (var i = 0; i < data.items.length; i++){
newsArray[i] = (data.items[i].title);
}
console.log(newsArray);
})}
// Refresh functions ever 10 minutes
rss()
setInterval(function slow() {
rss();
}, 600000); // 10 Minute refresh time
});
Check following code. You need to initialise listTicker once rss feed is loaded.
<script src='https://code.jquery.com/jquery-3.2.1.min.js'></script>
<script>
var listTicker = function(options) {
var defaults = {
list: [],
startIndex: 0,
interval: 3 * 1000,
}
var options = $.extend(defaults, options);
var listTickerInner = function(index) {
if (options.list.length == 0) return;
if (!index || index < 0 || index > options.list.length) index = 0;
var value = options.list[index];
options.trickerPanel.fadeOut(function() {
$(this).html(value).fadeIn();
});
var nextIndex = (index + 1) % options.list.length;
setTimeout(function() {
listTickerInner(nextIndex);
}, options.interval);
};
listTickerInner(options.startIndex);
}
var textlist = new Array("news1", "news2", "news3");
$(function() {
function rss() {
$.getJSON("https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.stuff.co.nz%2Frss", function(data) {
newsArray = [];
for (var i = 0; i < data.items.length; i++) {
newsArray[i] = (data.items[i].title);
}
console.log(newsArray);
listTicker({
list: newsArray,
startIndex: 0,
trickerPanel: $('#newsPanel'),
interval: 3 * 1000,
});
})
}
rss();
});
</script>
<div id='newsPanel' />

Replace and loop images after X milliseconds

I am having trouble getting this to work, I just want the images to loop endlessly. What isn't right here?
var croppingImages = new Array()
croppingImages[0] = "https://img.f1today.eu/x/topstory/58c7e187745517a1c90fc5ebe21c55da49223c999500b.jpg";
croppingImages[1] = "https://pbs.twimg.com/media/C69Y8aWW0AEkCIW.jpg:small";
setTimeout("animateImages()", 100);
var cropImg = 0;
function animateImages() {
document.getElementById("cropping__animation").src = croppingImages[cropImg]
x++;
}
<img src="https://img.f1today.eu/x/topstory/58c7e187745517a1c90fc5ebe21c55da49223c999500b.jpg" id="cropping__animation">
There are a couple of things here.
1) cropImg is never incremented, so animateImages will always show the same image
2) animateImages will only ever be called once by setTimeout
This code works better:
var cropImg = 0;
var croppingImages = new Array()
croppingImages[0] = "https://img.f1today.eu/x/topstory/58c7e187745517a1c90fc5ebe21c55da49223c999500b.jpg";
croppingImages[1] = "https://pbs.twimg.com/media/C69Y8aWW0AEkCIW.jpg:small";
animateImages();
function animateImages() {
document.getElementById("cropping__animation").src = croppingImages[cropImg];
if (++cropImg > croppingImages.length - 1)
{
cropImg = 0;
}
setTimeout(function() {
animateImages();
}, 3000);
}
https://jsfiddle.net/y6bhgm53/5/
if you want to loop them endless you maybe should use setInterval() and not setTimeout(). Also you should make it that your cropImg variable loops by checking if the value is greater than the array length.
https://jsfiddle.net/nyxeen/y6bhgm53/6/
I hope it helps
var croppingImages = new Array()
croppingImages[0] = "https://img.f1today.eu/x/topstory/58c7e187745517a1c90fc5ebe21c55da49223c999500b.jpg";
croppingImages[1] = "https://pbs.twimg.com/media/C69Y8aWW0AEkCIW.jpg:small";
setInterval(animateImages, 100);
var cropImg = 0;
function animateImages() {
document.getElementById("cropping__animation").src = croppingImages[cropImg]
cropImg++;
if(cropImg>=croppingImages.length)cropImg=0
}
<img src="https://img.f1today.eu/x/topstory/58c7e187745517a1c90fc5ebe21c55da49223c999500b.jpg" id="cropping__animation">

How to call JavaScript function repeatedly

I am trying to call the JavaScript function repeatedly after the execution.
function startSlide(){
var products = [
['images/product_images/footwear/footwear_1.jpeg'],
['images/product_images/mobile/mobile_1.jpeg'],
['images/product_images/camera/camera_1.jpeg'],
['images/product_images/fashion/fashion_1.jpeg'],
['images/product_images/laptop/laptop_1.jpeg'],
['images/product_images/furniture/furniture_1.jpeg']
];
for (var i = 0; i < products.length; i++) {
var image = products[i][0];
imgslider(image, i * 800);
}
};
function imgslider(image, timeout)
{
window.setTimeout(function() {
document.getElementById('imgslider').innerHTML = "";
var product = document.getElementById('imgslider');
var elem = document.createElement("img");
product.appendChild(elem);
elem.src = image;
},timeout);
startSlide();
}
The startSlide() function iterates the array and fetch the value from array and call the function imgslider(). the imgslider() function appends the image to the div.
at the end of the imgslider() i am trying to call the startSlide() so that it could continue the execution.... but its not working. how can i do this?
The problem is your code is creating an infinite recursion...
Maintianing your code structure you can add a flag to fix the problem
function startSlide() {
var products = [
['//placehold.it/64X64&text=1'],
['//placehold.it/64X64&text=2'],
['//placehold.it/64X64&text=3'],
['//placehold.it/64X64&text=4'],
['//placehold.it/64X64&text=5']
];
for (var i = 0; i < products.length; i++) {
var image = products[i][0];
imgslider(image, i * 800, i == products.length - 1);
}
};
function imgslider(image, timeout, last) {
window.setTimeout(function() {
document.getElementById('imgslider').innerHTML = "";
var product = document.getElementById('imgslider');
var elem = document.createElement("img");
product.appendChild(elem);
elem.src = image;
if (last) {
setTimeout(startSlide, 800);
}
}, timeout);
}
startSlide()
<div id="imgslider"></div>
If you want to loop, then you can use setInterval() instead
function startSlide() {
var products = [
['//placehold.it/64X64&text=1'],
['//placehold.it/64X64&text=2'],
['//placehold.it/64X64&text=3'],
['//placehold.it/64X64&text=4'],
['//placehold.it/64X64&text=5']
],
i = 0;
setInterval(function() {
imgslider(products[i][0]);
if (++i >= products.length) {
i = 0
}
}, 800);
};
function imgslider(image) {
document.getElementById('imgslider').innerHTML = "";
var product = document.getElementById('imgslider');
var elem = document.createElement("img");
product.appendChild(elem);
elem.src = image;
}
startSlide()
<div id="imgslider"></div>
That's because window.setTimeout only calls the function once, so you should use window.setInterval instead. Something like this:
window.setInterval(function () { /* code to update picture... */ }, 3000);
If it's still not working you can check the console log for errors.
That's F12 in IE or Ctrl+Shift+J in Chrome.

JS mini-game in grid, browser frozen after first replication

I'm trying to create a small game that replicate neighbors cells in a grid. I use a web worker that draw replicate cells every seconds. I'm able to replicate the first second. If my initial cell is row3col3, the new replicated cells will be :
row3col2, row3col4
row2col3, row4col3
The problem is, after the first second (and the replication), the game freezes, and i'm not able to do something. Can't click on cells, etc.
EDIT : After few seconds, it go to '00:02' but Chrome crashed "Aw, Snap! Something went wrong...' [RELOAD]
EDIT 2 : After looking on the memory used, It appears I have an memory overflow, 16000 Mb ! My method is bad, so.
I know my code is not really optimised, and I think that is the problem. Unfortunatly, i'm not able to do more efficient code, so I ask some help to you guys, to give me some ways to explore.
Here the code :
var lastClicked;
var cellTab = Array();
var replicant = Array();
var newReplicant = Array();
var count = 5;
var rows = 20;
var cols = 20;
var randomRow = Math.floor((Math.random() * rows));
var randomCol = Math.floor((Math.random() * cols));
var grid = clickableGrid(rows, cols,randomRow,randomCol,cellTab, function(el,row,col,i){
console.log("You clicked on element:",el);
console.log("You clicked on row:",row);
console.log("You clicked on col:",col);
console.log("You clicked on item #:",i);
$(el).addClass('clicked');
lastClicked = el;
});
document.getElementById("game").appendChild(grid);
function clickableGrid( rows, cols, randomRow, randomCol, cellTab, callback ){
var i=0;
var grid = document.createElement('table');
grid.className = 'grid';
for (var r=0;r<rows;++r){
var tr = grid.appendChild(document.createElement('tr'));
for (var c=0;c<cols;++c){
var cell = tr.appendChild(document.createElement('td'));
$(cell).addClass('row'+r+'col'+c);
if(randomCol == c && randomRow == r)
{
storeCoordinate(r, c, replicant);
$(cell).css('background', '#000000');
}
storeCoordinate(r, c, cellTab);
cell.addEventListener('click',(function(el,r,c,i){
return function(){
callback(el,r,c,i);
}
})(cell,r,c,i),false);
}
}
return grid;
}
function storeCoordinate(xVal, yVal, array)
{
array.push({x: xVal, y: yVal});
}
function replicate(replicant)
{
for (var i = 0; i < replicant.length; i++) {
console.log(replicant);
var supRowX = replicant[i].x-1;
var supRowY = replicant[i].y;
storeCoordinate(supRowX, supRowY, newReplicant);
var subRowX = replicant[i].x+1;
var subRowY = replicant[i].y;
storeCoordinate(subRowX, subRowY, newReplicant);
var supColsX = replicant[i].x;
var supColsY = replicant[i].y-1;
storeCoordinate(supColsX, supColsY, newReplicant);
var subColsX = replicant[i].x;
var subColsY = replicant[i].y+1;
storeCoordinate(subColsX, subColsY, newReplicant);
}
}
function drawReplicant(replicant, cellTab)
{
for (var i = 0; i < replicant.length; i++) {
if($.inArray(replicant[i], cellTab))
{
$('.row'+replicant[i].x+'col'+replicant[i].y).css('background', '#000000');
}
}
}
var w = null; // initialize variable
// function to start the timer
function startTimer()
{
// First check whether Web Workers are supported
if (typeof(Worker)!=="undefined"){
// Check whether Web Worker has been created. If not, create a new Web Worker based on the Javascript file simple-timer.js
if (w==null){
w = new Worker("w.countdown.js");
}
// Update timer div with output from Web Worker
w.onmessage = function (event) {
document.getElementById("timer").innerHTML = event.data;
console.log(event.data);
replicate(replicant);
replicant = newReplicant;
drawReplicant(replicant, cellTab);
};
} else {
// Web workers are not supported by your browser
document.getElementById("timer").innerHTML = "Sorry, your browser does not support Web Workers ...";
}
}
// function to stop the timer
function stopTimer()
{
w.terminate();
timerStart = true;
w = null;
}
startTimer();
And here, the web worker :
var timerStart = true;
function myTimer(d0)
{
// get current time
var d=(new Date()).valueOf();
// calculate time difference between now and initial time
var diff = d-d0;
// calculate number of minutes
var minutes = Math.floor(diff/1000/60);
// calculate number of seconds
var seconds = Math.floor(diff/1000)-minutes*60;
var myVar = null;
// if number of minutes less than 10, add a leading "0"
minutes = minutes.toString();
if (minutes.length == 1){
minutes = "0"+minutes;
}
// if number of seconds less than 10, add a leading "0"
seconds = seconds.toString();
if (seconds.length == 1){
seconds = "0"+seconds;
}
// return output to Web Worker
postMessage(minutes+":"+seconds);
}
if (timerStart){
// get current time
var d0=(new Date()).valueOf();
// repeat myTimer(d0) every 100 ms
myVar=setInterval(function(){myTimer(d0)},1000);
// timer should not start anymore since it has been started
timerStart = false;
}
Maybe it's because I use jQuery ?

Categories

Resources