Cannot replace a specific part of string - javascript

I've some problem with a string replace, in particular I've a php that return an array, each index of array contains a specific string of translation. So essentially, this array are saved inside: GlobalVariables.language['hello_world'], that for example return Hello world.
Now I've an array index that contains this translation string:
wait $seconds seconds before try again
I set the seconds inside an interval function that working as a countdown:
setInterval(function ()
{
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
text = text.replace('$seconds', seconds);
console.log(text);
$('.alert').text(text);
if (--timer < 0)
{
timer = 0; //Stoppo il timer
}
}, 1000);
this will return a string like this:
wait 20 seconds before try again
but only for the first time, 'cause later the $seconds part of the string is already replaced, I though to replace only digital number of text for second timing, but I can't do this 'cause before call setInterval I append the string to another that contains a digital number.
How can I solve this problem?

dont replace the original variable but use a different one.
text will then always contain $seconds:-
setInterval(function() {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
var text2 = text.replace('$seconds', seconds);
console.log(text2);
$('.alert').text(text2);
if (--timer < 0) {
timer = 0; //Stoppo il timer
}
}, 1000);

First time it works as $seconds is found in the string. However next time(2nd iteration onward) since $seconds not exists in the text, thus its not replaced.
You should persist original with element and used it as template.
//Perists original text with element
var alertElem = $('.alert');
alertElem.data('text', text);
setInterval(function (){
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
alertElem.text(function(){
return alertElem.data('text').replace('$seconds', seconds)
});
if (--timer < 0)
{
timer = 0;
}
}, 1000);

Related

Hiding div classes when timer ends in Javascript

I have a timer script but I am having a few issues with it. Just a day ago, it was working perfectly fine, as intended. Now, the timer no longer hides the div class when it ends. Didn't change the HTML or JavaScript code at all, but for whatever reason it no longer removes the div class.
Here is the JavaScript code:
function startTimer(duration, display) {
var timer = duration,
minutes,
seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;
display.textContent = minutes + ' ' + ' ' + seconds;
if (--timer < 0) {
display.textContent = 'OFFER HAS EXPIRED.';
$('.formme').css('visibility', 'hidden');
}
console.log(parseInt(seconds));
window.localStorage.setItem('seconds', seconds);
window.localStorage.setItem('minutes', minutes);
}, 1000);
}
window.onload = function() {
sec = parseInt(window.localStorage.getItem('seconds'));
min = parseInt(window.localStorage.getItem('minutes'));
if (parseInt(sec) == 0 && parseInt(min) == 0) {
$('#time').text('OFFER HAS EXPIRED.');
$('.formme').css('visibility', 'hidden');
} else {
var start = 5 * 60;
if (sec > 0 || min > 0) {
start = parseInt(min * 60) + sec;
}
// var start = 60 * 5;
display = document.querySelector('#time');
startTimer(start, display);
}
};
On top of that, I used localStorage to prevent the timer from resetting when the webpage is refreshed. However, when the timer is finished, instead of going straight to the "OFFER HAS EXPIRED" text, it counts down from 00:01 then displays the text. Can anyone help me out? Thanks in advance!

my couter time gets reset on page load

recently i implemented a count timer for my shopping website that sets a limit of 24 hours when they create an order and not check out with a payment,so that counter reminds him/her that have to make a payment. The timer that is in our table is the start time and is adjusted by the current time up to 24 hours - after that, the order is cancelled.
Now i have a problem, when i reload the page the counter restarts from 24 hours this is my code
<script type="text/javascript">
function startTimer(duration, display) {
var start = '<?php echo $pending_order_date;?>';
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
if(minutes >= 60){
hours = (minutes / 60) | 0;
minutes = (minutes % 60) | 0;
}else{
hours = 0;
}
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var twentyfourhour = 60 * 60 *24,
display = document.querySelector('#time');
startTimer(twentyfourhour, display);
};
</script>
Please see my code, i get the timestamp in php from my table and the count.
Your help would be appreciated.
You need to store your left off duration somewhere. localStorage seems to be better fit
function startTimer(duration, display) {
var start = '<?php echo $pending_order_date;?>';
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
if(minutes >= 60){
hours = (minutes / 60) | 0;
minutes = (minutes % 60) | 0;
}else{
hours = 0;
}
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
localStorage.setItem('timer', diff);
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var twentyfourhour = 60 * 60 *24,
display = document.querySelector('#time');
var timePassed = localStorage.getItem('timer');
startTimer((typeof timer!=='undefined' ? timer : twentyfourhour), display);
};
so each time your duration changes, it will update localStorage timer value. when you reload page, it will look for timer item in localStorage and will get that value, if it doesn't exist then will use 24 hrs. you may also add a controller to remove timer once it is expired, and store it with the order number or something so you can use multiple values. but this should give you an idea.

countdown timer with number reduction after set point?

I've got a working countdown timer which starts at 30 minutes.
With only 3 minutes left (so after 27 minutes) I'd like the number 250 to decrease at random intervals from 3 minutes left down to the end of the countdown.
Any ideas?
https://codepen.io/anon/pen/bWoGrb
// Stopwatch
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var thirtyMinutes = 60 * 30,
display = document.querySelector('#stopwatch');
startTimer(thirtyMinutes, display);
};
<div id='stopwatch'></div>
Maybe use something like this (I hope I clearly understood the question):
Just using a if/else within the condition something to say: Go normal when more than 60*3, and when under 60*3 seconds rest, there is chance to do nothing
// Stopwatch
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
if(timer > 60*3 || Math.random() < 0.25) {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
} else {
/* do not reduce the timer to wait 1 interval more */
/* or maybe do like `timer -= Math.random()` if you want to reduce it faster */
}
}, 1000);
}
window.onload = function () {
var thirtyMinutes = 60 * /*30*/ 4, // just set to 4 to see faster
display = document.querySelector('#stopwatch');
startTimer(thirtyMinutes, display);
};
<div id='stopwatch'></div>

jQuery time clock counter

I'm trying to make a simple jQuery Time counter just to count the user working time in my application displaying hours and minutes
HTML:
<body>
<div><input type="text" class="time"/></div>
</body>
JS:
function startTimer(duration) {
var timer = duration,hours, minutes;
setInterval(function () {
hours = parseInt(timer / 3600, 10)
minutes = parseInt(timer / 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
$('input[type=text].time').val(hours + ":" + minutes);
if (++timer < 0) {
timer = 0;
}
}, 1);
}
jQuery(function ($) {
var minutes = 0
startTimer(minutes);
});
Fiddle:
http://jsfiddle.net/df773p9m/1856/
The problem is that at this time the counter does not reset when reach 60 minutes and continues to count, although the hours were updated.
Notes: I've set the interval to 1 ms in order to test the operation.
you should use % after the division, otherwise it'll continue
check this updated jsfiddle
EDIT
Sean is right, I have fixed the code, the 24 should be in the % not the division also note that I'm multiplying duration by 60 to get the mins from the seconds
no need for the reset mins line anymore
function startTimer(duration) {
var timer = duration*60,hours, minutes;
setInterval(function () {
hours = parseInt((timer / 3600)%24, 10)
minutes = parseInt((timer / 60)%60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
$('input[type=text].time').val(hours + ":" + minutes);
if (++timer < 0) {
timer = 0;
}
}, 1);
}
jQuery(function ($) {
var minutes = 1339;
startTimer(minutes);
});
http://jsfiddle.net/df773p9m/1859/
If your timer is in minutes, and it's counting up one minute at a time, you want to divide the total time by 60 to get hours. Then you can get the remainder with the modulo operator % for the remaining minutes:
function startTimer(duration, display) {
var timer = duration,
hours,
minutes;
setInterval(function () {
hours = parseInt(timer / 60, 10);
minutes = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
$('#time').val(hours + ":" + minutes);
// I have no idea what you're trying to do here, it appears this will never evaluate to true:
if (++timer < 0) {
timer = duration;
}
}, 100); // this number should be changed to 60000 for it to be one minute (60,000 milliseconds = 1 minute)
}
jQuery(function ($) {
var minutes = 0,
display;
startTimer(minutes, display);
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder_()
Remainder (%)
The remainder operator returns the remainder left over when one
operand is divided by a second operand. It always takes the sign of
the dividend, not the divisor. It uses a built-in modulo function to
produce the result, which is the integer remainder of dividing var1 by
var2 — for example — var1 modulo var2. There is a proposal to get an
actual modulo operator in a future version of ECMAScript, the
difference being that the modulo operator result would take the sign
of the divisor, not the dividend.

I need some explanation for some of this code

This a count down timer. I don't understand how var timer works. What is its set value after each interval? How does the timer produce the number of minutes and seconds? Could some one break down step-by-step how this bit of code operates?
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
Here is the complete code:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
minutes = parseInt(timer / 60, 10);
Minutes are number of current total seconds divided by 60 (seconds in a minute).
E.g.: 65 / 60 = 1 minute. We just keep the integer part.
seconds = parseInt(timer % 60, 10);
Seconds are calculated as the module 60 of the current total seconds counter.
E.g.: 65 % 60 = 5 (1 minute, 5 seconds)
[Notice that in the second line the parseInt is unnecessary.]
var timer = duration, seconds, minutes;
this can also be written as:
var timer = duration;
var seconds;
var minutes;
You can declare and instialise multiple variables at a time in javascript.
var a,
b,
c;
is same as
var a;
var b;
var c;
also you can intialize variable too so
var timer = duration, seconds, minutes;
is same as writing
var timer = duration;
var seconds;
var minutes;
(as #Lorenzo already mentioned)
var timer = duration, seconds, minutes declares 3 variables with only the first getting initialized. It is the same as writing:
var timer = duration;
var seconds;
var minutes;

Categories

Resources