Use setTimeout to postpone time intensive processing while data entry taking place - javascript

I have a textarea that the user keys in some data. I need to read this data when it is changed and process it, the processing is very time consuming.
I have the textarea events: change keyup cut paste input call the function triggerProcess().
If one character only is typed into the textarea (or one character only is deleted) then needs to be get called triggerProcess().
If a word of several characters is typed in then the whole system grinds to a halt if triggerProcess() gets called for every character in that word. Even if the system did not grind to a halt it is pointless having triggerProcess() called for each character as the whole word plus the entire contents is what is required to be processed. However a single character such as "I", or a number may need to be processed.
I want to postpone the processing if the typist is typing a word or sentence (if the typist is fast ) but once they pause then their data is processed.
As soon as triggerProcess is called the first thing it does is clear a timer and then set another timer that calls the intensive processing when it expires.
My idea is to put a short timeout in triggerProcess of about 300ms so that there is always at least 300ms before the data is read from the textarea and processed. If one character say "I" is typed then that will be processed, but if several characters are typed in a sequence such as when a word is typed then triggerProcess is called by the textarea event watchers, the timer is cleared and started again for each character. When the word is finished and there is a gap in the stream from the keyboard into the text area the last started timer expires and the word is processed. I know that this will freeze the typist out while the text area contents is being processed, but that freeze out is much better than having the typist frozen out for each character.
How does my code look? Could something go terribly wrong? Could it be improved?
Thank you for taking the time to read this, all comments gratefully received.
Peter
var delayTimer; //global variable as opposed to local variable so that it can be cleared within function display.
function triggerProcess(){
clearTimeout(delayTimer);
delayTimer = 0;
delayTimer=setTimeout(function(){
// when the Timeout fires then
// read the data from the textarea and have some very time consuming work on it
},300);
}

What you are trying to achieve is called autocomplete.
Your code looks cool to me, but If I were you, I will not go for setTimeOut because that is a hack and will make the experience slow. I would think of AJAX call rather than a setTimeOut With AJAX (since the call is asynchronous), you can send request as many times as you want without user experiencing anything bad. Whenever the user types and change event will be called, it will ask for new matching words and will show the new matching words to user, when it has any.
I do not know if you use jQuery or not, but anyhow jQuery UI has one component (See here jQuery UI AUtocomplete). Since thank god jQuery UI is an open-source project, you can see the code at /ui/jquery.ui.autocomplete.js. If you open the other autocompleteEvents.js, you can see that there are four event types there: focus, close, select, change. As you can see in autocomplete example.
$.ajax({
//Where you load the data, could be a backend server instead of a
// XML file
url: "london.xml",
dataType: "xml",
success: function( xmlResponse ) {
//If matching any element from the london.xml file,
// Show the result in a menu or something
}
});
It is just calling whenever anything gets changed to get the new results (as simple as that). If you do not like AJAX, try to use callbacks, show the results after you sent the newly typed word and get a reply back and not in between.
Here is just another autocomplete example with my second suggestion in mind: complete.ly. It shares the same concept.
It just adds the onchange and keyup event:
if (txt.addEventListener) {
txt.addEventListener("input", handler, false);
txt.addEventListener('keyup', handler, false);
txt.addEventListener('change', handler, false);
}
And will make the callback whenever it is done with getting new values, checking if anything matches and will show the result:
var handler = function() {
var value = txt.value;
if (registerOnTextChangeOldValue !== value) {
callback(value);
}
};
Read the full source here: complete.ly source code
I hope I make sense and my answer helped!

Related

How to stop a setInterval Loop in Javascript outside of code without refreshing the browser?

This may be a quite naive question but I really need some help.
Prior to writing this post, I was programming on JSBin. Turns out without me realizing, I ran a setInterval loop prompting for userInput and it kept on looping, making me unable to click anywhere to change the code to fix the loop. It kept on repeating and repeating. It got to the point where I had to refresh and lose all my hard-written-code (I was not logged in, so my code was not saved)! I want to avoid that next time.
So, my question is how do I stop any such kind of setInterval Loops, so that I am able to access my code and change it and re-run it. Below is a code that demonstrates my issue, if you try running it on JSBin.com (obviously, it is not the code I wrote before). As you can see, I can not click on my code to change it (or save it) in any way, which means I lose all my code!
This may seem like a useless question, but I really want to know ways to fix it and perhaps fixing it from the developer tools will help me be familiar with the overwhelming set of tools it has :P. So please help me if you know a solution.
Thank you for taking your time to help me! I appreciate it.
setInterval(demo,1);
function demo()
{
var name = prompt("Enter your name: ");
}
Another option is to search the developer tools "Elements" panel for the iframe (this should be doable even if the main document is unresponsive due to prompt's blocking) - then, just right click the iframe element and remove it, no need to type any Javascript. (or, if you want you can select the iframe with querySelector and remove it, eg document.querySelector('iframe').remove())
That's kind of a hack and should only be used in cases like the one exposed in OP but,
About all implementations use integers as timerid that just get incremented at every call.
So what you can do, is to clear all timeouts that were created on the page.
To do so you need to first get to which timerid we are, then call cleatTimeout or clearInterval (they do the same) in a loop until you reach the last call:
function stopAllTimers() {
const timerid = setTimeout(_=>{}); // first grab the current id
let i=0;
while(i < timerid) {
clearTimeout(i); // clear all
i++;
}
};
btn.onclick = stopAllTimers;
// some stoopid orphan intervals
setInterval(()=>console.log('5000'), 5000);
setInterval(()=>console.log('1000'), 1000);
setInterval(()=>console.log('3000'), 3000);
const recursive = () => {
console.log('recursive timeout');
setTimeout(recursive, 5000);
};
recursive();
<button id="btn">stop all timeouts</button>
Assuming the dev tools are closed, hit esc and f12 nearly simultaneously. This should open the dev tools. If it doesn't keep trying until it does.
Once they are open, hit esc and f8. Again, retry til it halts javascript execution at some arbitrary point in the code.
In the "sources" tab locate the generated script for what you wrote (offhand I don't know how it would look like from within JSBin) and literally delete the var name = prompt("Enter your name: "); line. Hitting f8 again will continue execution as if the "new" code is running. This should free you up to copy/paste your code from the site itself before you refresh the page

Prevent user from pasting line break

I'm currently having an issue with a code. In my code, I've got a textarea where the user can enter the title of an article and I would like this article to be only in one row. That's why I wrote a script to prevent users to press the return key. But they could bypass this security, indeed if they copy/past the line break they could enter a line break. So, is there a way to detect line break ? I suppose we can do this with regular expressions and with \n or \n. However I tried this:
var enteredText = $('textarea[name="titleIdea"]').val();
var match = /\r|\n/.exec(enteredText);
if (match) {
alert('working');
}
and it doesn't work for an unknown reason. I think the var enteredText = $('textarea[name="titleIdea"]').val(); doesn't work because when I try to alert() it, it shows nothing. But something strange is that when I do an alert on $('textarea[name="titleIdea"]').val(); and not on the enteredText variable it shows the content.
Have a great day. (sorry for mistakes, I'm french)
if they copy/past the line break they could enter a line break
That's why you shouldn't even worry about preventing them from entering it - just don't save it. Remove it on the blur and input events if you really want to, but the only time it actually matters is before you save it to the database (or whatever you are using).
$('textarea[name="titleIdea"]').on('blur input', function() {
$(this).val($(this).val().replace(/(\r\n|\n|\r)/gm,""));
});
And, as other people have already mentioned, if they can't do line breaks, you shouldn't be using a textarea.
I assume your problem is with the paste event.
If i guessed this is my snippet:
$(function () {
$('textarea[name="titleIdea"]').on('paste', function(e) {
var data;
if (window.clipboardData) { // for IE
data = window.clipboardData.getData('Text');
} else {
data = e.originalEvent.clipboardData.getData('Text');
}
var match = /\r|\n/.exec(data);
if (match) {
alert('working');
console.log(data);
}
})
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<textarea name="titleIdea">
</textarea>
This needs to be handled in the backend. Even if you use the recommended appropriate HTML input type of text (instead of textarea), you still do not remove the possibility of return chars getting saved.
The two other answers use Javascript - which technically is the domain of this question. However, this can not be solved with Javascript! This assumes that the input will always come from the form you created with the JS function working perfectly.
The only way to avoid specific characters being inserted into your database is to parse and clean the data in the backend language prior to inserting into your database.
For example, if you are using PHP, you could run a similar regex that stripped out the \n\r chars before it went into processing.
Javascript only helps the UX in this case (the user sees what they will be saving). But the only way to ensure you have data integrity is to validate it on the server side.

password input masking with delay, android style in javascript/jquery

Let me start by saying that my task is complete. But I'm trying to get an understanding of how it's working, and one thing is confusing to me. In other words, I stumbled on the answer by accident.
My task was simple: in an input box, mask the input as the user types, by changing each character to * after a delay. This is how android phones handle masked input, slightly different than iPhone.
I used a combination of jQuery/javascript and regex. My working code:
$('.room_input').focus(function () {
currentFocus = $(this);
});
$('.key').click(function () {
setTimeout(function () {
currentFocus.val(currentFocus.val().replace(/[^\*]/, '*'));
}, 2000);
});
It's pretty simple, and it works great. When each key is pressed, it changes to * after 2 seconds. Each key is on its own timer. But there is one major thing I don't understand. When the callback from setTimeout triggers, the code above seems like it would set the entire contents of the textbox to *'s. Because the "replace" above replaces the entire content of the value with any characters not *.
But it doesn't. Each key changes after 2 seconds from when it was clicked (as it should).
Why is that? I'm thinking it might be the regex - does it only change the first match it finds? Did I just answer my own question?
UPDATE: I did.
It's the regex. It only replaces the first matched character in the string. I was thinking it maybe had something to do with single-threading issues... as usual, I'm making a problem much more difficult than it is. :)
Yep you are correct.
Every key click adds a character, and then starts a timer that later turns the first non-asterisk into an asterisk. It's far simpler than you might expect.

Whats happening? One day its OK, the next day its 'undefined'?

I am writing a greasemonkey script. Recently i had this same problem twice and i have no idea why is this happening.
function colli(){
.....
var oPriorityMass = bynID('massadderPriority');//my own document.getElementById() function
var aPriorities = [];
if (oPriorityMass) {
for (var cEntry=0; cEntry < oPriorityMass.childNodes.length; cEntry++) {
var sCollNumber = oPriorityMass.childNodes[cEntry].getAttribute('coll');
if (bynID('adder' + sCollNumber + '_check').checked)
aPriorities.push(parseInt(sCollNumber));
}
}
.....
}
So the mystery of this is, one day i had oPriorityMass named as oPririoty. It was working fine, but the whole function was not yet complete and i started working on another functions for my script. These functions have no connection with each other.
Few days later i decided to go back to my function in the above example and finish it. I ran a test on it without modifying anything and got an error in the firefox's (4) javascript error console saying that oPriority.chilNodes[cEntry] is undefined. NOTE, few days back i have tested it exactly the same way and there was no such problem at all.
Ok, so, i decided to rename oPriority to oPriorityMass. Magically, problem got solved.
At first i thought, maybe there was some conflict of 2 objects, with the same name being used in different functions, which somehow continued to live even outside of function scope. My script is currently over 6000 lines big, but i did a search and found out that oPriority was not mentioned anywhere else but in this exact function.
Can somebody tell me, how and why is this happening? I mentioned same thing happened twice now and they happened in different functions, but the same problem node.childNodes[c] is undefined yet node is not null and node.childNodes.length show correct child count.
What is going on? How do i avoid such problems?
Thank you
EDIT: The error given by error console is
Error: uncaught exception: TypeError: oPriorityMass.childNodes[cEntry] is undefined
In response to Brocks comment:
GM_log(oPriorityMass.childNodes[cEntry]) returns undefined as a message. So node.childNodes[c] is the thing that is undefined in general.
My script creates a div window. Later, the above function uses elements in this div. Elements do have unique IDs and i am 100% sure the original site don't know about them.
My script has a start/stop button to run one or the other function when i need to.
I have been refreshing the page and running my script function now. I have noticed that sometimes (but not always) script will fail with the described error on the first run, however, if i run it again (without refreshing the page) it starts working.
The page has a javascript that modifies it. It changes some of it's element widths so it changes when the browser is resized. But i know it has no effect on my div as it is left unchanged when i resize browser.
EDIT2:
function bynID(sID) {
return top.document.getElementById(ns(sID));
}
function ns(sText) {
return g_sScriptName + '_' + sText;
}
ns function just adds the script name in front of the ID. I use it when creating HTML element so my elements never have the same id as the web page. So bynID() is simple function that saves some typing time when i need to get element by ID.
I have modified my colli() function to include check
if (oPriorityMass) {
if (!oPriorityMass.childNodes[0]) {
GM_log('Retrying');
setTimeout(loadPage,2000);
return;
}
for (var cEntry=0; cEntry < oPriorityMass.childNodes.length; cEntry++) {
var sCollNumber = oPriorityMass.childNodes[cEntry].getAttribute('coll');
if (bynID('adder' + sCollNumber + '_check').checked)
aPriorities.push(parseInt(sCollNumber));
}
}
The loadPage function does 1 AJAX call, then i run few XPATH queries on it, but the actual contents are never appended/shown on the page, just kept inside document.createElement('div'), then this function calls colli(). So now, as i have modified my function, i checked the error console and saw that it may take up to 5 tries for it to start working correctly. 5 x 2seconds, thats 10 seconds. It is never 5 retries always, may vary There's got to be something else going on?
In Firefox, childNodes can include #text nodes. You should check to make sure that childNodes[cEntry] has nodeType == 1 or has a getAttribute method before trying to call it. e.g.
<div id="d0">
</div>
<div id="d1"></div>
In the above in Firefox and similar browsers (i.e. based on Gecko and WebKit based browsers like Safari), d0 has one child node, a text node, and d1 has no child nodes.
So I would do something like:
var sCollNumber, el0, el1;
if (oPriorityMass) {
for (var cEntry=0; cEntry < oPriorityMass.childNodes.length; cEntry++) {
el0 = oPriorityMass.childNodes[cEntry];
// Make sure have an HTMLElement that will
// have a getAttribute method
if (el0.nodeType == 1) {
sCollNumber = el0.getAttribute('coll');
el1 = bynID('adder' + sCollNumber + '_check');
// Make sure el1 is not falsey before attempting to
// access properties
if (el1 && el1.checked)
// Never call parseInt on strings without a radix
// Or use some other method to convert to Number
aPriorities.push(parseInt(sCollNumber, 10));
}
}
Given that sCollNumber seems like it is a string integer (just guessing but it seems likely), you can also use:
Number(sCollNumber)
or
+sCollNumber
whichever suits and is more maintainable.
So, according to your last edit, it now works, with the delay, right?
But when I suggested the delay it was not meant to do (even more?) ajax calls while waiting!!
NOT:
if (!oPriorityMass.childNodes[0]) {
GM_log('Retrying');
setTimeout(loadPage,2000);
return;
More like:
setTimeout (colli, 2000);
So the ajax and the other stuff that loadPage does could explain the excessive delay.
The random behavior could be caused by:
return top.document.getElementById(ns(sID));
This will cause erratic behavior if any frames or iframes are present, and you do not block operation on frames. (If you do block such operation then top is redundant and unnecessary.)
GM does not operate correctly in such cases -- depending on what the script does -- often seeming to "switch" from top scope to frame scope or vice versa.
So, it's probably best to change that to:
return document.getElementById (ns (sID) );
And make sure you have:
if (window.top != window.self) //-- Don't run on frames or iframes
return;
as the top lines of code.
Beyond that, it's near impossible to see the problem, because of insufficient information.
Either boil the problem into a Complete, Self Contained, Recipe for duplicating the failure.
OR, post or link to the Complete, Unedited, Script.

Javascript events

I am completely confused here. So I am looking for a solution for the following problem:
I want to trigger some function(for now an alert box) using jQuery on an input field. Conditions are:
Input field always maintains the focus.
Input is fed from a USB device, which acts just like a keyboard input. So for 10 characters, there will be 10 keydown and keyup events.
Once input is filled with 10 characters, respective alert box should pop out.
Now the problem I am facing, how do I find out that input fed in is not equal to 10 characters, so throw an error alert box.(lets say just 5 chars came in input, how do I figure out the final count is 5, because there will be 5 keyup events)
You could show a message underneath/beside the input box instead of popping an alert box.
E.g. on every keyup event, check the string length, and if it's not 10, show that message.
If you really, really have to resort to alert box, you could do a timeout check, e.g. only perform the validation after 1000ms of key event inactivity. This could get very annoying on the user though.
You really have two problems here. One is just understanding the jQuery syntax (see the second part to my answer), and the other is - what is the best way to understand WHEN to throw up an error box.
To answer the second question first, my recommendation would be to not use an alert box to warn the user as they tend to be modal and really interrupt the flow of input. Secondly, as you said - how do you know when the person has stopped "typing." Unless you use some sort of timing mechanism (which is more trouble than it's worth), you don't. My suggestion would be to utilize a "div" within your HTML that shows there is an error UNTIL you reach 10 characters. Once that happens, you can hide the div. (And, of course, the div can be styled to look pretty in the meantime.)
So...how to do this...
Let's assuming your input field has an id of "myField." If you are using jQuery (which is in your tags), you would do something like this.
$(function() {
var keypresses = 0;
$('#myField').keyUp(function () {
keypresses++;
if(keypresses == 10) {
$('#error').hide(); // This is your div error with some error text in it.
// Do other stuff.
} else {
// Display an error.
}
});
Alternatively, if you don't want to use the keypresses variable, you can also use..
if($(this).val().length == 10) { }
The real issue is the fact that you are measuring in key press events, because not all key presses (even when the field has focus) will insert a character into field (for example returnesc). Therefore, you will need to measure the string length in order to validate the code before you start executing functions.
In actuality you don't even need jQuery to accomplish what you need, just bind the function call to a key press event, and only execute the function call if yourstring.length = 10
yourInput.onKeyPress(yourString.length = 10 && yourFunction());
Try -
$('#idofinputfield').keyUp(function () {
var length = $('#idofinputfield').val().length;
if(length <= 10){
alert("less than 10");
}else{
alert("greaterthan 10");
}
});

Categories