how can i make game over function in memory card game? - javascript

i need to make function, this function check if all the cards matched and i reach to the end of the game or not .
i do class called hidden for matched cards and make condition check if all cards include this class this mean i reach to the end if not this mean i can continue playing.
the problem that the condition don't work perfectly and always active else condition
enter code here
var images = ["fas fa-american-sign-language-interpreting" , "fas fa-american-sign-language-interpreting" , "fas fa-cut" ,"fas fa-cut", "fas fa-bicycle" , "fas fa-bicycle" ,"fas fa-asterisk","fas fa-asterisk","fas fa-atom","fas fa-atom","fas fa-car-crash","fas fa-car-crash", "fas fa-chess", "fas fa-chess", "fas fa-drum" , "fas fa-drum"];
var image_card=images.length-3;
var image_start=0;
var oppened_card=[];
var matched_card=[];
var Showen_card=[];
var moves=0;
var unmatch_element = [];
Shuffle(images);
const game_structure = document.getElementById('game_structure');
const fragment = document.createDocumentFragment();
for (let i=0 ; i<images.length ; i++){
var card= document.createElement("section");
var front = document.createElement("div");
var back = document.createElement("div");
front.classList.add("front");
back.classList.add("back");
card.appendChild(front);
card.appendChild(back);
back.innerHTML=`<i class="${images[i]}"></i>`;
fragment.appendChild(card);
}
game_structure.appendChild(fragment);
game_structure.addEventListener('click' , element_Listener);
function Shuffle(array){
var i= array.length , tempValue , randomindex ;
while (--i >0){
randomindex = Math.floor(Math.random() * (i+1));
tempValue = array[randomindex];
array[randomindex] = array[i] ;
array[i] = tempValue ;
}
return array;
}
function element_Listener(event){
if (event.target.nodeName === 'SECTION') {
startTimer();
console.log(event.target.childNodes);
if (oppened_card.length<2){
flip_Card(event);
}
}
}
function flip_Card(event){
event.target.childNodes[0].classList.add('front_ro');
event.target.childNodes[1].classList.add('back_ro' , "open");
if(oppened_card.length==0){
oppened_card.push(event.target.childNodes[1].innerHTML);
matched_card.push(event.target);
console.log(matched_card[0]);
}
else if(oppened_card.length==1){
oppened_card.push(event.target.childNodes[1].innerHTML);
matched_card.push(event.target);
moveCounter();
if (oppened_card[0]==oppened_card[1]){
match();
**// here i invoke the function**
var finished_game = game_over();
console.log(finished_game);
oppened_card=[];
}
else{
// unmatch();
}
}
}
function moveCounter(){
moves++;
document.getElementById("steps").innerHTML = moves ;
}
function match(){
var allCards = document.getElementsByClassName("flip");
matched_card[0].classList.add('cardAnimate');
console.log(matched_card[0].childNodes[1]);
matched_card[1].classList.add('cardAnimate');
setTimeout(function(){
matched_card[0].classList.add('hidden');
matched_card[1].classList.add('hidden');
},1000);
oppened_card=[];
}
let timerRunning = false;
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var gameTime;
function startTimer(){
if(!timerRunning){
timerRunning = true;
var totalSeconds = 0;
gameTime=setInterval(setTime, 1000);
}
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
}
function stopTimer(){
if(timerRunning){
timerRunning = false;
clearInterval(gameTime);
}
}
**// here is the beginning of my function**
var checked_classes =[];
function game_over(){
var hidden_cards = document.getElementsByTagName('section');
for (let hidden_card of hidden_cards){
console.log(hidden_card.classList.contains("hidden"));
let checked_class = hidden_card.classList.contains("hidden");
checked_classes.push(checked_class);
}
if (checked_classes.includes('false') == true){
return false;
}
else {
return true;
}
}
i expect to return false when the game has unmatched cards but it return true always.

You are pushing booleans to the checked_classes array, but checking if it contains a string. This causes the contain method to always return false. Try searching for a boolean instead.
if (checked_classes.includes(false)){
return false;
}
else {
return true;
}
}

Related

js / css flip card game bug in shuffle function

I have created a js memory game. It has a 24-card grid, and it is supposed to shuffle randomly out of a deck of 15 cards in order to create a little variety. The game should be different every time. However, at random the game shuffles the initial deck and builds the board with 11 pairs and one non-pair of cards. Here's the whole js file:
`var score;
var cardsmatched;
var ui = $("#gameUI");
var uiIntro =$("#gameIntro");
var uiStats = $("# gameStats");
var uiComplete = $("#gameComplete");
var uiCards = $("#cards");
var uiScore = $(".gameScore");
var uiReset = $(".gameReset");
var uiPlay = $("#gamePlay");
var uiTimer = $("#timer");
var matchingGame = {};
matchingGame.deck = ['grilledfish', 'grilledfish','barbacoa', 'barbacoa','tripa', 'tripa','bajafish', 'bajafish','carneasada', 'carneasada','carnitas', 'carnitas', 'chorizoasado','chorizoasado','shrimptaco','shrimptaco','decabeza','decabeza','alpastor', 'alpastor','dorados','dorados', 'lengua','lengua','chicharron','chicharron','sudados','sudados', 'polloasado','polloasado',];
$(function(){
init();
});
function init() {
uiComplete.hide();
uiCards.hide();
playGame = false;
uiPlay.click(function(e){
e.preventDefault();
uiIntro.hide();
startGame();
});
uiReset.click(function(e){
e.preventDefault();
uiComplete.hide();
reStartGame();
});
}
function startGame(){
uiTimer.show();
uiScore.html("0 seconds");
uiStats.show();
uiCards.show();
score = 0;
cardsmatched= 0;
if (playGame == false) {
playGame = true;
matchingGame.deck.sort(shuffle);
for (var i=0; i<25; i++){
$(".card:first-child").clone().appendTo("#cards");
}
uiCards.children().each(function(index) {
$(this).css({
"left" : ($(this).width() + 20) * (index % 6),
"top" : ($(this).height() + 20) * Math.floor(index / 6)
});
var pattern = matchingGame.deck.pop();
$(this).find(".back").addClass(pattern);
$(this).attr("data-pattern",pattern);
$(this).click(selectCard);
});
timer();
};
}
function timer(){
if (playGame){
scoreTimeout = setTimeout(function(){
uiScore.html(++score = "seconds");
timer();
}, 1000);
};
};
function shuffle() {
return 0.5 - Math.random();
}
function selectCard(){
if($(".card-flipped").size()> 1){
return;
}
$(this).addClass("card-flipped");
if($(".card-flipped").size() == 2) {
setTimeout(checkPattern, 1000);
};
};
function checkPattern(){
if (isMatchPattern()) {
$(".card-flipped").removeClass("card-flipped").addClass("card-removed");
if(document.webkitTransitionEnd){
$(".card-removed").bind("webkitTransitionEnd", removeTookCards);
}else{
removeTookCards();
} else {
$(".card-flipped").removeClass("card-flipped");
}
}
function isMatchPattern(){
var cards = $(".card-flipped");
var pattern = $(cards[0]).data("pattern");
var anotherPattern = $(cards[1]).data("pattern");
return (pattern == anotherPattern);
}
function removeTookCards() {
if (cardsmatched < 12) {
cardsmatched++;
$(".card-removed").remove();
}else{
$(".card-removed").remove();
uiCards.hide();
uiComplete.show();
clearTimeout(scoreTimeout);
}
}
function reStartGame(){
playGame = false;
uiCards.html("<div class='card'><div class='face front'></div><div class='face back'></div></div>");
clearTimeout(scoreTimeout);
matchingGame.deck = ['grilledfish', 'grilledfish','barbacoa', 'barbacoa','tripa', 'tripa','bajafish', 'bajafish','carneasada', 'carneasada','carnitas', 'carnitas', 'chorizoasado','chorizoasado','shrimptaco','shrimptaco','decabeza','decabeza','alpastor', 'alpastor','dorados','dorados', 'lengua','lengua','chicharron','chicharron','sudados','sudados', 'polloasado','polloasado',];
startGame();
}
`

Setinterval not firing at individual times - and uncaught typeerror

On the function on this code, whatareyousingingpatrick(),, when the function is called a new element and setinterval should be called, however it doesn't seem like a new one is created with a new original variable, it just seems like the same one gets fired over and over. Thanks for your help
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<!DOCTYPE html>
<body onclick="whatareyousingingpatrick();" onkeypress="pretend();">
<span id="money">25</span>$ - <span id="lives">100</span>/100 lives - Level: <span id="level">1</span>
<br><br>
<span style="background-color:#c3c3c3;width:1000px;height:175px;overflow:hidden;position:relative;display:block;" id="track"></span>
<br>
<span id="divthing" style="position:relative;display:block;"></span>
<script>
money = 25;
lives = 100;
mycars = {};
function doofus() {
if($("div:first").offset().left > 1000){
$("div:first").remove();
lives = lives-1;
document.getElementById("lives").innerHTML = lives;
}
}
function dodat() {
var btn = document.createElement("div");
btn.style.width = "25px";
btn.style.height = "25px";
btn.style.backgroundColor = "red";
btn.style.boxShadow = "inset 0px 0px 0px 2px black";
btn.style.position = "absolute";
btn.style.left = "0px";
btn.style.webkitTransition = "opacity 1s";
var numba = Math.round(Math.random() * 50);
btn.class = "haha";
btn.id = numba;
mycars[numba] = -50;
var move = function () {
mycars[numba] = mycars[numba] + 1.5;
document.getElementById(numba).style.left = mycars[numba] + "px";
if(mycars[numba] > 100 && mycars[numba] < 150){
document.getElementById(numba).style.top = mycars[numba]/0.5-200 + "px";
}
};
setInterval(move, 10);
document.getElementById("track").appendChild(btn);
}
setInterval(dodat, 2000);
setInterval(doofus, 200);
function dis1() {
$("shooter").css("background-color", "red");
setTimeout('$("shooter").css("background-color", "blue");', '1000');
compareEl = $("#shoot1");
// Let's find the closest block!
var otherEls = $('div'),
compareTop = compareEl.offset().top,
compareLeft = compareEl.offset().left,
winningScore = Infinity,
score, winner, curEl;
otherEls.each(function () {
// Calculate the score of this element
curEl = $(this);
score = Math.abs(curEl.offset().left - compareLeft);
if (score < winningScore) {
winningScore = score;
winner = this;
}
});
document.getElementById(winner.id).style.opacity="0";
money = money+1;
document.getElementById("money").innerHTML=""+money+"";
}
function dis2() {
compareEl2 = $("#shoot2");
// Let's find the closest block!
var otherEls2 = $('div'),
compareTop2 = compareEl2.offset().top,
compareLeft2 = compareEl2.offset().left,
winningScore2 = Infinity,
score2, winner2, curEl2;
otherEls2.each(function () {
// Calculate the score of this element
curEl2 = $(this);
score2 = Math.abs(curEl2.offset().left - compareLeft2);
if (score2 < winningScore2) {
winningScore2 = score;
winner2 = this;
}
});
document.getElementById(winner2.id).style.opacity="0";
}
function dis3() {
compareEl3 = $("#shoot3");
// Let's find the closest block!
var otherEls3 = $('div'),
compareTop3 = compareEl3.offset().top,
compareLeft3 = compareEl3.offset().left,
winningScore3 = Infinity,
score3, winner3, curEl3;
otherEls3.each(function () {
// Calculate the score of this element
curEl3 = $(this);
score3 = Math.abs(curEl3.offset().left - compareLeft3);
if (score3 < winningScore3) {
winningScore3 = score;
winner3 = this;
}
});
document.getElementById(winner3.id).style.opacity="0";
}
function dis4(){
compareEl4 = $("#shoot4");
// Let's find the closest block!
var otherEls4 = $('div'),
compareTop4 = compareEl4.offset().top,
compareLeft4 = compareEl4.offset().left,
winningScore4 = Infinity,
score4, winner4, curEl4;
otherEls4.each(function () {
// Calculate the score of this element
curEl4 = $(this);
score4 = Math.abs(curEl4.offset().left - compareLeft4);
if (score4 < winningScore4) {
winningScore4 = score;
winner4 = this;
}
});
document.getElementById(winner4.id).style.opacity="0";
}
original = 0;
function whatareyousingingpatrick(){
if(money >= 1){
money = money+10000000;
original = original+1;
setInterval("dis"+original+"();alert("+original+");", 1800);
var btn = document.createElement("shooter");
btn.style.display = "block";
btn.id = "shoot"+original+"";
btn.style.height = "25px";
btn.style.width = "25px";
btn.style.backgroundColor = "blue";
btn.innerHTML = "<img src='http://www.bubblews.com/assets/images/news/1317280976_1370202845.png' style='height:100%;width:100%;border-radius:100%;opacity:0.7;'>";
btn.style.borderRadius= "100%";
btn.style.boxShadow= "0px 0px 200px 75px rgba(0, 0, 0, 0.2)";
btn.style.position = "absolute";
btn.style.left = event.pageX-20;
btn.style.top = event.pageY-250;
document.getElementById("divthing").appendChild(btn);
}
else{
alert("Sorry, this dude costs over 25 bucks.");
}
}
function pretend(){
if(money >= 60){
money = money-60;
if (event.keyCode == 49) {
alert("You have bought the FASTER SHOOTING upgrade for your first missile. Note that you can purchase this upgrade an unlimited number of times.");
setInterval("dis1();", "1000");
}
if (event.keyCode == 50) {
alert("You have bought the FASTER SHOOTING upgrade for your second missile. Note that you can purchase this upgrade an unlimited number of times.");
setInterval("dis2();", "1000");
}
if (event.keyCode == 51) {
alert("You have bought the FASTER SHOOTING upgrade for your third missile. Note that you can purchase this upgrade an unlimited number of times.");
setInterval("dis3();", "1000");
}
if (event.keyCode == 52) {
alert("You have bought the FASTER SHOOTING upgrade for your fourth missile. Note that you can purchase this upgrade an unlimited number of times.");
setInterval("dis4();", "1000");
}
}
else
{
alert("Sorry, the cost of the FASTER SHOOTING upgrade for this missile is 60$");
}
}
</script>
<script>
setTimeout('document.getElementById("level").innerHTML="2";setInterval(dodat, 8000);', '40000');
</script>
<br><br>
Here it is isolated.
original = 0;
function whatareyousingingpatrick(){
if(money >= 1){
money = money+10000000;
original = original+1;
setInterval("dis"+original+"();alert("+original+");", 1800);
var btn = document.createElement("shooter");
btn.style.display = "block";
btn.id = "shoot"+original+"";
btn.style.height = "25px";
btn.style.width = "25px";
btn.style.backgroundColor = "blue";
btn.innerHTML = "<img src='http://www.bubblews.com/assets/images/news/1317280976_1370202845.png' style='height:100%;width:100%;border-radius:100%;opacity:0.7;'>";
btn.style.borderRadius= "100%";
btn.style.boxShadow= "0px 0px 200px 75px rgba(0, 0, 0, 0.2)";
btn.style.position = "absolute";
btn.style.left = event.pageX-20;
btn.style.top = event.pageY-250;
document.getElementById("divthing").appendChild(btn);
}
else{
alert("Sorry, this dude costs over 25 bucks.");
}
}
When I try:
setInterval(function(){
var func = 'dis' + original;
func();
alert(original); //for some reason
}, 1800);
I keep getting Uncaught TypeError: string is not a function. Any clue why?
You are trying to call a function on a string variable.
var func = 'dis' + original;
so func is now a string not a callable function.
If the resultant string func is actualltly a function name you could do this:
window[func]();
To call func with a string variable.

Javascript not working while inserting image object in html

MAJOR EDIT: Re-Did a lot of things. But similar error.
var white = 1;
var turn = white;
var table = document.getElementById("game");
function createTable(table, white) {
var i,j,tr;
for(i=0;i<8;i++)
{
tr = document.createElement('tr');
for(j=0;j<8;j++)
tr.appendChild(document.createElement('td')).id = String.fromCharCode( (white == 1 ? j : 8-j) +97)+(white == 1 ? 8-i : i+1);
table.appendChild(tr);
}
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
table.rows[i].cells[j].setAttribute("class","cell");
}
}
}
function onImageLoad(t) {
console.log(t);
}
function createImageArray() {
var w,c,p;
var image = new Array(2);
for(w=0;w<2;w++)
{
image[w] = new Array(2);
for(c=0;c<2;c++)
{
image[w][c] = new Array(6);
for(p=0;p<6;p++)
{
image[w][c][p] = new Array(2);
}
}
}
return image;
}
function createBlankimageArray() {
var blank = new Array(2);
return blank;
}
function bufferImages(image,blank) {
var w, c, p, s, word;
for(w=0;w<2;w++)
{
for(c=0;c<2;c++)
{
for(p=0;p<6;p++)
{
for(s=0;s<2;s++)
{
word = w.toString() + c.toString() + (p+1).toString() + s.toString() + ".png";
//console.log(word);
image[w][c][p][s] = new Image();
image[w][c][p][s].onload = onImageLoad(word);
image[w][c][p][s].src='final images/'+ word;
}
}
}
}
for(i=0;i<2;i++)
{
blank[i] = new Image();
word = i.toString() + '.png';
blank[i].onload = onImageLoad(word);
blank[i].src= 'final images/'+ word;
}
}
function intializeState() {
var x,y,temp;
var state = new Array(8);
for(y=0;y<8;y++)
{
state[y] = new Array(8);
for(x=0;x<8;x++)
{
state[y][x] = new Array(3);
// Set Cell White or Black.
state[y][x][0] = (x+y)%2;
if(y==1 || y == 6)
{
temp = 0;
state[y][x][1] = temp;
state[y][x][2] = ( white==1 ? 0 : 1);
}
else if(x==0 || x==7) {temp = 1;}
else if(x==1 || x==6) {temp = 2;}
else if(x==2 || x==5) {temp = 3;}
else if(x==3) {temp = 4;}
else if(x==4) {temp = 5;}
if(temp!=0)
{
if(y==0)
{
state[y][x][1] = temp;
state[y][x][2] = (white == 1 ? 0 : 1);
}
else if(y==7)
{
state[y][x][1] = temp;
state[y][x][2] = (white == 1 ? 1 : 0);
}
else
{
state[y][x][1] = 7;
state[y][x][2] = 7;
}
}
}
}
return state;
}
function drawState(table,state,image,blank) {
var y,x;
//var table = document.getElementById("game");
var w,c,p;
for(y=0;y<8;y++)
{
for(x=0;x<8;x++)
{
c = state[y][x][0];
w = state[y][x][1];
p = state[y][x][2];
if(p!=7)
{
table.rows[y].cells[x].appendChild(image[w][c][p][0]);
}
else
{
table.rows[y].cells[x].appendChild(blank[c]);
}
}
}
}
var state = intializeState();
var image = createImageArray();
var blank = createBlankimageArray();
createTable(table, white);
bufferImages(image,blank);
intializeState(state);
drawState(table,state,image,blank);
HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Anti Chess</title>
<link rel="stylesheet" type="text/css" href="screen2.css">
</head>
<body>
<h1 id="game_title">Anti Chess by theManikJindal</h1>
Visit Blog!
<br />
<br />
<table id="game"></table>
<script src="req_logic.js"></script>
</body>
</html>
The above script is required to create a chess board in the initial position.
The problem that I am encountering is in the drawState function.
Console: (has printed out all the image names after loading them) After that:
Uncaught TypeError: Cannot read property '1' of undefined req_logic.js:154
Which is the line: table.rows[y].cells[x].appendChild(image[w][c][p][0]);
so where have I gone wrong.
EDIT: jsFiddle.net link : http://jsfiddle.net/8H3Ha/1/
Change the definition ot initializeState() to:
function intializeState() {
var x,y,temp;
var state = new Array(8);
for(y=0;y<8;y++)
{
state[y] = new Array(8);
for(x=0;x<8;x++)
{
state[y][x] = new Array(3);
// Set Cell White or Black.
state[y][x][0] = (x+y)%2;
if(y==1 || y == 6)
{
temp = 0;
state[y][x][1] = temp;
state[y][x][2] = ( white==1 ? 0 : 1);
}
else if(x==0 || x==7) {temp = 1;}
else if(x==1 || x==6) {temp = 2;}
else if(x==2 || x==5) {temp = 3;}
else if(x==3) {temp = 4;}
else if(x==4) {temp = 5;}
if(temp!=0)
{
if(y==0)
{
state[y][x][1] = temp;
state[y][x][2] = (white == 1 ? 0 : 1);
}
else if(y==7)
{
state[y][x][1] = temp;
state[y][x][2] = (white == 1 ? 1 : 0);
}
else
{
state[y][x][1] = 7;
state[y][x][2] = 7;
}
}
}
}
return state;
}
Then call it as:
state = initializeState();
The problem is that the parameter variable named state was shadowing the global variable with the same name inside initializeState.
I also suggest that the elements of the state array should be objects, not arrays. Arrays should be used when the elements are uniform, but each of these sub-elements have different purposes: [0] is the cell color, [1] is the piece, and [2] is the piece color.

function is undefined in firefox only

ok, the following code works ok in IE7+ and Chrome.
but for some reason, xfade is undefined in firefox
<html>
<body>
<div id="slider"></div>
<script type="text/javascript">
var Klimateka = {
Slider: function () {
// Check if we have a slider div on page
var slider = document.getElementById('slider');
if (slider != null) {
var images = ["slide-image-1.jpg", "slide-image-2.jpg", "slide-image-3.jpg", "slide-image-4.jpg"];
var i = images.length;
while (i) {
i -= 1;
var img = document.createElement("img");
img.src = "images/" + images[i];
slider.appendChild(img);
}
var d = document, imgs = new Array(), zInterval = null, current = 0, pause = false;
imgs = d.getElementById("slider").getElementsByTagName("img");
for (i = 1; i < imgs.length; i++) imgs[i].xOpacity = 0;
imgs[0].style.display = "block";
imgs[0].xOpacity = .99;
setTimeout("xfade()", 3500);
function xfade() {
cOpacity = imgs[current].xOpacity;
nIndex = imgs[current + 1] ? current + 1 : 0;
nOpacity = imgs[nIndex].xOpacity;
cOpacity -= .05;
nOpacity += .05;
imgs[nIndex].style.display = "block";
imgs[current].xOpacity = cOpacity;
imgs[nIndex].xOpacity = nOpacity;
setOpacity(imgs[current]);
setOpacity(imgs[nIndex]);
if (cOpacity <= 0) {
imgs[current].style.display = "none";
current = nIndex;
setTimeout(xfade, 3500);
} else {
setTimeout(xfade, 50);
}
function setOpacity(obj) {
if (obj.xOpacity > .99) {
obj.xOpacity = .99;
return;
}
obj.style.opacity = obj.xOpacity;
obj.style.MozOpacity = obj.xOpacity;
obj.style.filter = "alpha(opacity=" + (obj.xOpacity * 100) + ")";
}
}
}
},
bar: function () {
}
};
Klimateka.Slider();
i have setup a jsfiddler for testing:
http://jsfiddle.net/rTtKh/10/
This might only apply to Firefox:
functions do not hoist when declared inside a child block.
You declare xfade inside the if block, but you are calling it prior to the declaration:
setTimeout(xfade, 3500);
Put the function declaration on top.
You have to do the same with setOpacity inside xfade. <- That is not necessary.
Fix your line that says this: setTimeout("xfade()", 3500); to match your others:
setTimeout(xfade, 3500);
Use setTimeout(xfade, 3500) instead.

javascript countdown with showing milliseconds

I want to do a count down and want to show like format as Minutes:Seconds:Milliseconds. I made a count down with jquery plug-in countdown but it shows just Minutes:Seconds format.
Is there any way to make it right?
Many Thanks!
Hi guys I have developed a code for my self use the following code
counter for 20 seconds
var _STOP =0;
var value=1999;
function settimer()
{
var svalue = value.toString();
if(svalue.length == 3)
svalue = '0'+svalue;
else if(svalue.length == 2)
svalue = '00'+svalue;
else if(svalue.length == 1)
svalue = '000'+svalue;
else if(value == 0)
svalue = '0000';
document.getElementById('cn1').innerHTML = svalue[0];
document.getElementById('cn2').innerHTML = svalue[1];
document.getElementById('cn3').innerHTML = svalue[2];
document.getElementById('cn4').innerHTML = svalue[3];
value--;
if (_STOP==0 && value>=0) setTimeout("settimer();", 10);
}
setTimeout("settimer()", 10);
Try this: http://jsfiddle.net/aamir/TaHtz/76/
HTML:
<div id="timer"></div>
​
JS:
var el = document.getElementById('timer');
var milliSecondsTime = 10000;
var timer;
el.innerHTML = milliSecondsTime/1000;
timer = setInterval(function(){
milliSecondsTime = milliSecondsTime - 1000;
if(milliSecondsTime/1000 == 0) {
clearTimeout(timer);
el.innerHTML = 'BOOOOM';
}
else {
el.innerHTML = milliSecondsTime/1000;
}
},1000);
​
If you want to make your own timer.
read this earlier question
How to create a JQuery Clock / Timer
Try setting the format parameter - http://keith-wood.name/countdownRef.html#format
On further reading, this plugin doesn't do milliseconds. At this point, you either have to edit the actual plugin code or find a new plugin.
I completely agree with #Matt Ball's comment.It may also cause the browser to crash.
Why don't you try this solution instead
jQuery 1 minute countdown with milliseconds and callback
I did it like this (generic counter from N to X (X > N)):
var dynamicCounterAddNewValue = 20;
var currentDynamicUpdater;
function dynamicCounterForValueForControlUpdater(_updaterData) {
_updaterData.from += dynamicCounterAddNewValue;
if (_updaterData.from > _updaterData.to) {
_updaterData.from = _updaterData.to;
}
_updaterData.c.html(_updaterData.from.toString());
if (_updaterData.from < _updaterData.to) {
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
10,
{
c: _updaterData.c,
from: _updaterData.from,
to: _updaterData.to
}
);
}
else {
clearTimeout(currentDynamicUpdater);
}
return;
}
// _c -> jQuery object (div,span)
// _from -> starting number
// _to -> ending number
function dynamicCounterForValueForControl(_c, _from, _to) {
clearTimeout(currentDynamicUpdater);
dynamicCounterForValueForControlUpdater(
{
c: _c,
from: _from,
to: _to
}
);
return;
}
EDIT: Updated version (more flexible - for N elements one after another):
(input element is Array of elements for making them dynamic-counts)
var dynamicCounterTimeout = 10;
var currentDynamicUpdater;
function odcArray(_odca) {
this.odca = _odca;
return;
}
function odc(_c, _from, _to) {
this.c = _c; // $('#control_id')
this.from = _from; // e.g. N
this.to = _to; // e.g. M => (M >= N)
var di = parseInt(_to / 45, 10);
if (di < 1) {
di = 1;
}
this.dynamicInc = di;
return;
}
function dynamicCounterForValueForControlUpdater(_odca) {
if (
_odca.odca === null
||
!_odca.odca.length
) {
clearTimeout(currentDynamicUpdater);
return;
}
var o = _odca.odca[0];
o.from += o.dynamicInc;
if (o.from > o.to) {
o.from = o.to;
_odca.odca.shift(); // Remove first element
}
o.c.html(o.from.toString());
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
dynamicCounterTimeout,
_odca
);
return;
}
function dynamicCounterForValueForControl(_odca) {
clearTimeout(currentDynamicUpdater);
// SETUP all counters to default
for (var i = 0; i < _odca.odca.length; i++) {
_odca.odca[i].c.html(_odca.odca[i].from.toString());
}
dynamicCounterForValueForControlUpdater(
_odca
);
return;
}

Categories