Specific textarea behaviour related to setTimeout - javascript

what I am trying to do is give the user a textarea (with enabled input) and allow him to write up to 10 chars. Actually, the textarea should ALLOW more chars, not only 10, and the other chars would behave accordingly:
1º There is a setTimeout whenever the user is on the 11ºchar. So, I'm writing something there, I reach the char number 10º (the "maximum" allowed of text) and want that other char to be erased AFTER a given time.
somethinge = 10 chars.
anotherwor = 10 chars.
input: somethingeiefjaiehf
after 5 seconds:
input: somethinge
input: anotherwordtotestthisandseeifitworks
after 5 seconds:
input: anotherwor
2ºTo accomplish this I basically attached a clearTimeout to a global variable:
//Function "countChar(val)" is activated with the keydown event
var timer_to_op = null;
function countChar(val) {
var len = val.value.length; //lenght of input in textarea
clearTimeout(timer_to_op);
//...
//irrelevant code
//...
}else if(len > 140){
$("#status_toOp_num").text(145-len);
timer_to_op = setTimeout(function(){
val.value = val.value.substring(0, 140);
},5000);
}
Actually, for some reason, it won't work. If the user is typing AND he types another char within the 5 seconds then I want the timer to restart.
input: anotherwor
input: anotherword (+d) timer = 1...2...3...
input: anotherworde (+e) timer = 1...2...
input: anotherwordef (+f) timer = 1...2...3...4...5!
input: anotherwor the user took more than 5 seconds so it erased the excedent.
Hope I got my point through. Any ideas on this one? Thank you very much! (I didn't put any html, it's only <textarea onclick="countChar(this)"> )

I didn't really try to understand what you are doing in your code, seems unnecessarily complicated.
Check this fiddle out. http://jsfiddle.net/Q2h5f/
HTML
<textarea id="limitText">0123456789</textarea>
Javascript
var tarea = document.getElementById("limitText");
tarea.onkeypress = checkInputText;
var timer = null;
function checkInputText(e) {
if (timer) clearTimeout(timer);
timer = setTimeout(limitTextLength, 5000);
}
function limitTextLength() {
var tareaVal = document.getElementById("limitText").value.toString();
if (tareaVal.length > 10) {
tarea.value = tareaVal.slice(0, 10);
}
}
Should solve your issue.

Related

How can I clear the random quotes output field?

I've made a random quote generator, it works properly with the only drawback - first quote is done, I click for the next one, it begins to appear in the output field, but the previous quote is still here(
I've tried location.reload(), but it simply keeps my output clean.
Please, advice, how can I fix that?
var source,
adress,
source_length,
start = 0,
randNum;
var quotes[some, examples, inside, etc];
function flowText(){
randNum = Math.floor(Math.random()*quotes.length);
source = quotes[randNum];
console.log(source);
adress = document.getElementById('wind');
source_length = source.length;
flow();
//location.reload();
}
function flow(){
adress.innerHTML += source.substr(start, 1);
start+=1;
if(start < source_length){
setTimeout("flow()", 100);
}
}
If you don't want adress to retain the previous quote
adress.innerHTML = '';
Then call flow();

Browser Crashes before Input is Entered

I'm writing a program in javascript that is supposed to be a fast paced typing challenge. The issue is that my script that's checking for input is crashing my browser before I can enter anything. I thought that it'd pause to wait for input but it seems like I might be wrong?
Here is the function that crashes my browser:
var level1 = function () {
var letter;
var ascii;
var ncorrect = 0;
var input = "0";
var timedout = false;
document.getElementById('prompt').text = "Level 1 : Type Here!" // this is supposed to change text on the page... It doesn't work but not that's not my question.
while (ncorrect < 26){
timedout = false;
setTimeout(timedout = true, 5000);
ascii = Math.floor(Math.random() * 122) + 97; // ASCII's of lower case letters
letter = String.fromCharCode(ascii);
document.getElementById('letter').text = letter;
input = document.getElementById('keyinput');
console.log(input);
if(!timedout && input === letter) {
clearTimeout();
ncorrect++;
}
else {
ncorrect = 0;
}
}
return 0;
}
If it's not a simple fix...
What would be a better way of monitoring input and responding to a right answer?
Thanks, I know it's a little broad of a question but I'm struggling to figure out what I'm looking for.
Javascript is already running an event loop in the background, so you don't need your own. This loop runs continuously and checks to see if any events have fired on any of the HTML DOM Elements. For example, if a button has been clicked, the event loop will pick up a click event for that element. You can add event handlers to the element, which are functions that fire when certain events occur to that element. What you want to do is set an event handler for the event that fires whenever the text in your input area (I'm assuming that the user is typing in an input or textarea tag) is fired.
For example, the following simple program will create a typing challenge 100 random characters long
var ncorrect = 0;
var timedout = false;
//select an empty paragraph to fill with text
var challengeText = document.getElementbyId("challengeText");
challengeText.innerHtml = "";
//Append 100 random characters to the paragraph
for (var i=0;i<100;i++) {
challengetText.innerHtml += String.fromCharCode(Math.floor(Math.random() * 122) + 97);
}
//Check the number of characters typed since the last the loop hit the element
var lastCharsTyped = 0;
var charsTyped = 0;
//Grab the user input
var input = document.getElementById("userInput")
//Set the event handler to fire when the user presses a key (technically, when they lift their finger
input.onkeyup = function(keyEvent){
//Ugly ternary to deal with the fact that not all browsers use the same api. If you haven't seen this before it means if which is a key of keyEvent then keyCoe is event.which, otherwise it's event.keyCode
var keyCode = ('which' in keyEvent) ? keyEvent.which : keyEvent.keyCode;
//Check if the key pressed is equal to the character in the text to match at the same position
if (keyCode === challengeText.innerHtml.charCodeAt(input.value.length)) { ncorrect ++} else {ncorrect = 0;}
}
It won't handle deletes or shift very gracefully, but it should give you an idea of the direction to take.
As a stylistic note, its customary to declare and initialize your variables right before you use them, rather than at the start of your program.
You can use setTimeout() and pass in a function that checks the input after whichever time you specify. Here's one way to implement this:
setTimeout( function () {
var textbox = document.getElementById('textbox');
if (textbox.value !== 'The quick brown fox jumps over the lazy dog.') {
alert('You didn\'t pass.');
} else {
alert('Congratulations!');
}
}, 5000);
Type in the phrase "The quick brown fox jumps over the lazy dog."
<input type="textbox" id="textbox"></input>
setTimeout is passed a function expression that checks user input and spits out an alert based on their typing prowess. The second argument 5000 means the function passed into setTimeout will be called at the nearest opportunity after 5000 ms has passed.

Delaying regex for more specific matches

I have a scenario where I need to run regex tests on a numeric input that represents phone company operator services.
In one instance, there is a prefix 118 which can act on its own or with a suffix of up to two digits.
At the moment, my function looks something like the below. My problem is that the least specific '118' exact match fires before the more specific one.
There is no sleep/wait in Javascript and unless I'm mistaken, I don't think I can get setTimeout to return a simple "return true" ?
I don't mind if the answer to this question is in pure Javascript or Jquery, but not having a dependency on Jquery would be preferable.
function isOperatorService(vNumber) {
var vNumber = vNumber.replace(/\D/g,'');
if (/^((44){0,1}118[0-9]{3})$/.test(vNumber)) {
console.log("118 specific");
return true;
}
if(/^((44){0,1}[19]{1}[0-9]{1}[0-79]{1})$/.test(vNumber)) {
console.log("Other shortcodes");
return true;
}
return false;
}
UPDATE: Re: "Provide your input and expected output."
Pretty much as I described above, in Pseudo-code :
if == 118
wait incase the user has not finished typing (e.g. wait incase 118118...)
else
do other regex cheks
Add a simple debouncer:
var timeout;
var typeDelay = 300; // wait after last type
var changeEvents = "propertychange keyup input paste change";
$('#yourinput').on(changeEvents, function () {
//clear your timeout
clearTimeout(timeout);
// Add another listener
timeout = setTimeout(function () {
// Do your regex here
function_ended_typing();
}, typeDelay);
});

jQuery - Variable Increment +1

I've had a look round and I'm a little confused.
There seems to be several responses to my particular problem but I don't fully understand.
So if anybody could help that'd be great!
Basically, I set a variable
var firstThumb = "02"
And I want to increase it
function thumbIncrease() {
firstThumb++
};
on an interval
setInterval(function(){
getThumb.trigger("click");
thumbIncrease();
}, 5000);
Basically what I expect to happen is -
Every 5 seconds a click is triggered, and I want my firstThumb variable to increase by 1.
So 02, click, 03, click, 04, click....
So each time it clicks a different element.
Any help would be great!
Thanks!!
EDIT
Thanks for the responses! I kind of understand now! So the reason I've got a 0, is more for me than for the code. I currently have 15 things that I need clicking. 01 and 15 being 2 characters, meaning my code looks neater. Should I just man up and remove the 0? Or is there a better way of doing it?
var counter = 1;
setInterval(function() {
var _text = counter + "<br>";
$("div").append(_text);
counter++;
},5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
</div>
If you want it to replace the old number use .html() instead of .append()
"01" is a string, 1 is a number you can increment.
If you just need zero padding:
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
var thumbNumber = "02";
thumbNumber = parseInt(thumbNumber);
var nextNumber = pad(++thumbNumber,2);
console.log(nextNumber);
Live Demo -- http://jsfiddle.net/v02vgw6w/2/

How to reset stop watch for multiple stop watch time?

I am trying to use multiple stop watch timer by using anchor tag.I have successfully done but I am not able to add a functionality like if I clicked first timer,It will start timer from zero,when I clicked second one,first timer's value will be zero and second one will start timer from zero.I am giving my working code below :
JS:
var digit=0;
var hrs = 0;
var min=0;
var time;
var timer_is_on=0;
var id;
function timer(id){
//[Old] - this should be placed after you increment digit
// document.getElementById("secs").innerHTML = digit
//alert("I am testing value"+id);
//[New]
// get the numerical value for seconds,minutes,hours
digit = parseInt(document.getElementById("secs"+id).innerHTML);
min = parseInt(document.getElementById("mins"+id).innerHTML);
hrs = parseInt(document.getElementById("hrs"+id).innerHTML);
// increment;
digit=digit+1;
if(digit>"59"){
min = parseInt(min)+1;
// why is this code here
var count = min.toString().length;
digit=0;
}
// [old] checking if second is greater than 59 and incrementing hours
// if(digit>"59"){
// [new] check if minute is greater than 59
if(min > "59"){
hrs=parseInt(hrs)+1;
digit=0;
min=0; // minute should be reset as well
}
// set the values after all processing is done
document.getElementById("secs"+id).innerHTML = format(digit);
document.getElementById("mins"+id).innerHTML= format(min);
document.getElementById("hrs"+id).innerHTML=format(hrs);
}
function activate(id){
if(!timer_is_on){
timer_is_on=1;
// time = setTimeout("timer()",1000) will only call it once , use setInterval instead
time=setInterval("timer("+id+")",1000);
}
else {
timer_is_on=0;
clearInterval(time); // clear the timer when the user presses the button again and reset timer_is_on
}
return id;
}
// left pad zero if it is less than 9
function format(time){
if(time > 9)
return time;
else return "0"+time;
}
And The HTML code I have used are :
Click here to start the timer
<span id="hrs1" >00</span>:<span id="mins1" >00</span>:<span id="secs1">00</span></strong>
<br/>
Click here to start the timer
<span id="hrs2" >00</span>:<span id="mins2" >00</span>:<span id="secs2">00</span>
Here is my working js fiddle demo : http://jsfiddle.net/EPtFW/1/
as you are using same method activate() to start second timer, it will make first timer as zero if timer already running.
Solution is "you have to maintain multiple unique timer ids for multiple timers"
For Example, let's say you have T1 and T2 timers to start time;
var timerMap={};
timerMap[createUniqueId for T1] = setInterval();
timerMap[createUniqueId for T2] = setInterval();
to clear timers
clearInterval(timerMap[createUniqueId for T1]);
clearInterval(timerMap[createUniqueId for T2]);
In your case, you have to have createUniqueId and adding to timerMap should be in activate() method. they will work independently.

Categories

Resources