javascript countdown with showing milliseconds - javascript

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;
}

Related

How to make an autofill for input type 1 letter at a time?

var addy = "1234567812345678"
function fillAddy(i) {
var addyKey = addy.substring(0, (addy.length - (addy.length - i) * -1))
$('*[placeholder$="number"]').val(addyKey);
}
for (i = 1; i < addy.length; i++) {
setTimeout(fillAddy(i), 2000);
}
I'm trying to make it so when it fills in addy in the input "[placeholder$="number"]" that it fills it one letter at a time with a 2 second delay each time it adds a letter/number, for some reason it fills it all in at once.
You can achieve that by using CSS animations:
#keyframes animated-text{
from {width: 0;}
to {width: 472px;}
}
View running jsfiddle. Update the width as per your requirements.
If you need to draw the letters one by one, setTimeout() won't work for loops. Instead you'll need to write recursive(self invoking) function.
Please, take a look at the example, hope this works for you.
<div class="div"></div>
var $textOldContainer = $('.div');
var textNew = 'New text';
var textOld = 'old text';
var textOldLength = textOld.length;
var textOldCnt = textOldLength;
var secondTime = false;
function loopChar() {
if( !secondTime ) {
setTimeout(function() {
if( textOldCnt <= textOldLength && textOldCnt >= 0 ) {
loopChar();
textOldCnt --;
$textOldContainer.text( textOld.substring(0, textOldCnt - 1) );
}
if( textOldCnt == 0 ) {
secondTime = true;
}
}, 10);
} else {
setTimeout(function() {
if( textOldCnt <= textNew.length ) {
loopChar();
textOldCnt++;
$textOldContainer.text( textNew.substring(0, textOldCnt - 1) );
}
}, 50);
}
}
loopChar();
Here is the demo Demo

Incrementing page number with JavaScript

I tried to figure out why the following code doesn't increment the page number, excepting from 1 to 2, but I couldn't find out.
<script>
var n = 1;
function increment() {
return ++n;
}
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "Timp rămas: "+secs+" secunde.";
if(secs < 1) {
clearTimeout(timer);
window.location.replace('question.php?n='+increment(n));
element.innerHTML += 'Click here now';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
Ideas?
Try this:
var params = new URL(document.location).searchParams;
var n = params ? params.get('n') || 1 : 1;
So n is read from URL and not set to 1 everytime a page is loaded.
Edit: ah, and maybe:
var timer = setTimeout(function(){countDown(secs, elem);},1000);

This Javascript function keeps looping, how can i make it run once?

The code is meant to animated some text in a typing fashion. I want it to run once, but it keeps looping through the area of sentences. How would i go about stopping it looping through. The top of the code gathers the value of a input and puts into the array, this all works fine. It is just the looping i am having issues with.
var yourWord = document.getElementById("myText").value;
var yourtext = "I took the word " + yourWord + "...";
var infomation = [yourtext,
'I looked at the most relevant news article relating to it...',
'And created this piece of art from the words in the article! '
],
part,
i = 0,
offset = 0,
pollyLen = Polly.length,
forwards = true,
skip_count = 0,
skip_delay = 5,
speed = 100;
var wordflick = function () {
setInterval(function () {
if (forwards) {
if (offset >= infomation[i].length) {
++skip_count;
if (skip_count == skip_delay) {
forwards = false;
skip_count = 0;
}
}
} else {
if (offset == 0) {
forwards = true;
i++;
offset = 0;
if (i >= pollyLen) {
i = 0;
}
}
}
part = infomation[i].substr(0, offset);
if (skip_count == 0) {
if (forwards) {
offset++;
} else {
offset--;
}
}
$('#pollyInfo').text(part);
}, speed);
};
$(document).ready(function () {
wordflick();
});
Modify the line:
setInterval(function () {
into:
var interval = setInterval(function () {
and then clear the interval where you are setting i=0;
if (i >= pollyLen) {
i = 0;
}
to:
if (i >= pollyLen) {
i = 0;
clearInterval(interval);
}
This should do the job!

jQuery continues even if user has left the page

I want to make a page that runs a jQuery script when user gets in the page and the query runs even if user leaves the page or closes the browser. Is this possible?
if(localStorage.getItem("counter")){
if((localStorage.getItem("counter") >= 300) || (localStorage.getItem("counter") <= 0)){
var value = 300;
}else{
var value = localStorage.getItem("counter");
}
}else{
var value = 300;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function (){
if(value <= 0){
localStorage.setItem("counter", 0);
value = 0;
$( ".exit" ).trigger( "click" );
}else{
value = parseInt(value)-1;
localStorage.setItem("counter", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function (){counter();}, 1000);
This is my script. For more detail, this is a countdown from 300 that when user gets in the page it starts and I want to make it like it runs even if user has left the page till it gets 0.
I dare to answer your question and nevertheless hope this will help you. There is no chance to run this js-code after this tab has been closed but you can remember the time an user left your site by setting a time_leave that is set on each interval-round and when an user leaves your site using onbeforeunload:
var value;
if (localStorage.getItem('counter')) {
if ((localStorage.getItem('counter') >= 300) || (localStorage.getItem('counter') <= 0)) {
value = 300;
} else {
value = getElaspedTime();
}
} else {
value = 300;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function () {
if (value <= 0) {
localStorage.setItem('counter', 0);
value = 0;
//$('.exit').trigger('click');
} else {
value = parseInt(value) - 1;
localStorage.setItem('counter', value);
}
document.getElementById('divCounter').innerHTML = value;
// set "departure"-time
localStorage.setItem('time_leave', (new Date()).getTime());
};
function getElaspedTime() {
var now = new Date();
var timeLeft = + localStorage.getItem('time_leave');
timeLeft = new Date(timeLeft);
var passedSecs = (now.getTime() - timeLeft.getTime()) / 1000;
return parseInt(localStorage.getItem('counter')) - parseInt(passedSecs);
}
window.onbeforeunload = function(){
// set "departure"-time when user closes the tap
localStorage.setItem('time_leave', (new Date()).getTime());
};
var interval = setInterval(function () {
counter();
}, 1000);

jQuery password generator

I have the following JS code that checks a password strength and also creates a random password as well. What I want to do is edit the code so that instead of putting the generated password inside the password field it will put it inside a span tag with say an id of randompassword. In addition that I would like it so that by default there will be a random password inside the span tag and then when the user clicks the button it will generate another one. And also move the link to be next to span tag rather than the password box.
Thanks.
Here is the code:
$.fn.passwordStrength = function( options ){
return this.each(function(){
var that = this;that.opts = {};
that.opts = $.extend({}, $.fn.passwordStrength.defaults, options);
that.div = $(that.opts.targetDiv);
that.defaultClass = that.div.attr('class');
that.percents = (that.opts.classes.length) ? 100 / that.opts.classes.length : 100;
v = $(this)
.keyup(function(){
if( typeof el == "undefined" )
this.el = $(this);
var s = getPasswordStrength (this.value);
var p = this.percents;
var t = Math.floor( s / p );
if( 100 <= s )
t = this.opts.classes.length - 1;
this.div
.removeAttr('class')
.addClass( this.defaultClass )
.addClass( this.opts.classes[ t ] );
})
.after('Generate Password')
.next()
.click(function(){
$(this).prev().val( randomPassword() ).trigger('keyup');
return false;
});
});
function getPasswordStrength(H){
var D=(H.length);
if(D>5){
D=5
}
var F=H.replace(/[0-9]/g,"");
var G=(H.length-F.length);
if(G>3){G=3}
var A=H.replace(/\W/g,"");
var C=(H.length-A.length);
if(C>3){C=3}
var B=H.replace(/[A-Z]/g,"");
var I=(H.length-B.length);
if(I>3){I=3}
var E=((D*10)-20)+(G*10)+(C*15)+(I*10);
if(E<0){E=0}
if(E>100){E=100}
return E
}
function randomPassword() {
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$_+?%^&)";
var size = 10;
var i = 1;
var ret = ""
while ( i <= size ) {
$max = chars.length-1;
$num = Math.floor(Math.random()*$max);
$temp = chars.substr($num, 1);
ret += $temp;
i++;
}
return ret;
}
};
$(document)
.ready(function(){
$('#password1').passwordStrength({targetDiv: '#iSM',classes : Array('weak','medium','strong')});
});
// you can use another improved version to generate password as follows
//Define
function wpiGenerateRandomNumber(length) {
var i = 0;
var numkey = "";
var randomNumber;
while( i < length) {
randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
if ((randomNumber >=58) && (randomNumber <=90)) { continue; }
if ((randomNumber >=91) && (randomNumber <=122)) { continue; }
if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
i++;
numkey += String.fromCharCode(randomNumber);
}
return numkey;
}
// Call
var myKey=wpiGenerateRandomNumber(10); // 10=length
alert(myKey);
// Output
2606923083
This line:
$(this).prev().val( randomPassword() ).trigger('keyup');
is inserting the value after a click. So you can change that value to stick the password wherever you want it. For example you could change it to:
$('span#randompassword').html(randomPassword());
You could also run this when the page loads to stick something in that span right away:
$(document).ready(function(){
$('span#randompassword').html(randomPassword());
});
//Very simple method to generate random number; can be use to generate random password key as well
jq(document).ready( function() {
jq("#genCodeLnk").click( function() {
d = new Date();
t = d.getTime();
jq("#cstm_invitecode").val(t);
});
});

Categories