How to insert delay into onkeyup event - delay

How would insert the delay into this snippet of code so that it won't fire till after the user is done typing?
JS
gridContainer = $('#shuffleContainer');
var sizer = gridContainer.find('.col-md-4');
$('.js-shuffle-search').on('keyup change', function () {
var val = this.value.toLowerCase();
gridContainer.shuffle('shuffle', function ($el, shuffle) {
// Only search elements in the current group
if (shuffle.group !== 'all' && $.inArray(shuffle.group, $el.data('groups')) === -1) {
return false;
}
var text = $.trim($el.find('.picture-item__title').text()).toLowerCase();
return text.indexOf(val) !== -1;
});
});
JS DELAY
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('input').keyup(function() {
delay(function(){
alert('Time elapsed!');
}, 1000 );
});

Related

how to make quick.db read async

I want to make this read calls async. It should output to the console 'finish' and then 'done'.
But the script wait first to finish the loop. Why it's not working?
const db = require('quick.db');
var balance = null;
var items = null;
final();
console.log('finish');
async function final() {
var res = await test();
console.log('done');
}
async function test() {
return new Promise((resolve, reject) => {
for(var i=0; i<10000; i++) {
balance = db.get('userInfo.balance') // -> 1000
items = db.get('userInfo.items') // ['Sword', 'Watch']
}
resolve(true);
});
}
So I have just copied and pasted your code and it works just the way you described it. It prints 'finish' and then 'done'. I'm not sure what's your question. However, I have a question about your code: Why would you use async and implicitly return a new Promise?
In addition to the above, you're trying to read some values from the db and they have not been set previously. I edited a bit your code:
const db = require('quick.db');
var balance = null;
var items = null;
db.set('userInfo', { difficulty: 'Easy' });
db.add('userInfo.balance', 1000);
db.push('userInfo.items', 'Sword');
db.push('userInfo.items', 'Watch');
final();
console.log('finish');
async function final() {
var res = await test();
console.log(`Balance: ${balance} | Items: ${items}`);
console.log('done');
}
async function test() {
for (var i = 0; i < 10000; i++) {
balance = db.get('userInfo.balance'); // -> 1000
items = db.get('userInfo.items'); // ['Sword', 'Watch']
}
}
Does it address your question?

Array is empty, no data after for loop added

I'm using redis and nodejs for the first time, without success. Trying to loop insert data but got an empty array.
const redis = require("redis");
const client = redis.createClient({
retry_strategy: function(options) {
if (options.error && options.error.code === "ECONNREFUSED") {
// End reconnecting on a specific error and flush all commands with
// a individual error
return new Error("The server refused the connection");
}
if (options.total_retry_time > 1000 * 60 * 60) {
// End reconnecting after a specific timeout and flush all commands
// with a individual error
return new Error("Retry time exhausted");
}
if (options.attempt > 10) {
// End reconnecting with built in error
return undefined;
}
// reconnect after
return Math.min(options.attempt * 100, 3000);
},
});
var data_value = {
id: '235235',
totalrv: 'WAIT',
product: 'productName2',
url: 'url2',
process: 'proc',
task: 'msg'
};
client.set("key0", JSON.stringify(data_value));
client.set("key1", JSON.stringify(data_value));
client.set("key2", JSON.stringify(data_value));
client.set("key3", JSON.stringify(data_value));
client.set("key4", JSON.stringify(data_value));
//client.get("key2", redis.print);
var logger_data = {
logger: []
};
client.keys('*', function (err, keys) {
if (err) return console.log(err);
for(var i = 0, len = keys.length; i < len; i++) {
var values_v = client.get(keys[i].toString(), function(err, val) {
// console.log(logger_data);
// data is exist ...
logger_data.logger.push(JSON.parse(val));
});
}
});
// empty data
console.log(logger_data);
I wrote 2 print data result, in the loop it's working ok, but end of function, there are no data in array.
you can call a function inside the callback if you want to print the logger_data with values outside the asynchronous callback, like this
function printLoggerData(){
console.log(logger_data);
}
client.keys('*', function (err, keys) {
if (err) return console.log(err);
for(var i = 0, len = keys.length; i < len; i++) {
var values_v = client.get(keys[i].toString(), function(err, val) {
// console.log(logger_data);
// data is exist ...
logger_data.logger.push(JSON.parse(val));
// calling the function here so that it contains the latest values
printLoggerData();
});
}
});
Ok, with help of CertainPerformance, it's now working in asynchronous.
Thank you very much ...
async function getMessage () {
var logger_data = {
logger: []
};
return new Promise(function(resolve, reject) {
client.keys('*', function (err, keys) {
if (err) return console.log(err);
for(var i = 0, len = keys.length; i < len; i++) {
var values_v = client.get(keys[i].toString(), function(err, val) {
logger_data.logger.push(JSON.parse(val));
resolve(logger_data);
});
}
});
});
}
async function main() {
let message = await getMessage();
console.log(message);
}
main();

Why doesn't my async function return any result?

I wrote this small program to fetch data. This however is done async. Since I nonetheless need to use the function holeVertreter(kzl) as a function in another module, I'd like to get a return value which I can eventually pass on.
Excuse my spaghetti code (I usually prettify the code when I am done with my task ...).
Credentials are stored in a file and are therefore not found in this file.
I'd like to end up with "vertreter" as a return value.
Thank you in advance.
const node = require("deasync");
const DSB = require('dsbapi');
const tabletojson = require('tabletojson');
const https = require('https');
const cred = require("./vertrCred");
const dsb = new DSB(cred["dsb"]["user"], cred["dsb"]["passw"]); //Sanitized - no Credentials here
//Stackoverflow 2332811
String.prototype.capitalize = function(lower) {
return (lower ? this.toLowerCase() : this).replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};
function holePlan(kuerzel) {
dsb.fetch()
.then(data => {
const timetables = DSB.findMethodInData('timetable', data);
const tiles = DSB.findMethodInData('tiles', data);
var tilesStr = JSON.stringify(tiles["data"][0]["url"]);
var url = JSON.parse(tilesStr);
https.get(url, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end',() => {
var tableasjson = tabletojson.convert(data);
var erstetab = tableasjson[0];
var zweitetab = tableasjson[1];
var drittetab = tableasjson[2];
var viertetab = tableasjson[3];
var fuenftetab = tableasjson[4];
var sechstetab = tableasjson[5];
var siebtetab = tableasjson[6];
var achtetab = tableasjson[7];
if (typeof kuerzel === "undefined")
{
var regenechse = '(Aaa|Aaa[A-Za-z?]|[A-Za-z?]Aaa)';
}
else {
var name = kuerzel.capitalize(true);
var regenechse = '('+name+'|'+name+'[A-Za-z?]|[A-Za-z?]'+name+')';
}
const regex = new RegExp(regenechse,'g');
var sammel = Object.assign(drittetab,fuenftetab);
var z= 0;
var vertreter = {}
var y = JSON.parse(JSON.stringify(sammel));
for (i=0;i<y.length;i++) {
if (typeof y[i].Vertreter =='undefined') {
}
else {
if(y[i].Vertreter.match(regex))
{
z += 1;
vertreter[z] = y[i];
}
}
}
if (z == 0) {
// console.log("Es gibt nichts zu vertreten");
}
else {
//console.log("Es werden "+z+" Stunden vertreten");
return (vertreter);
} ;
});
})
})
.catch(e => {
// An error occurred :(
console.log(e);
});
}
//Stackoverflow
function warte(promise) {
var done = 0;
var result = null;
promise.then(
function (value) {
done = 1;
result = value;
return (value);
},
function (reason) {
done = 1;
throw reason;
}
);
while (!done)
node.runLoopOnce();
return (result);
}
function holeVertretung(kzl) {
var aufgabe = new Promise((resolve,reject) => {
setTimeout(resolve,1000,holePlan(kzl));
});
var ergebnis = warte(aufgabe);
if (typeof ergebnis === "undefined") {
console.log("Mist");
}
else {
console.log(ergebnis);
}
return ergebnis;
}
holeVertretung("Aaa");
That's not the right way to work with promises. If you do such infinite loop, it beats the whole purpose of using promises. Instead, return value from the promise, and use async-await like this:
function warte(promise) {
var done = 0;
var result = null;
return promise.then(
...
}
async function holeVertretung(kzl) {
var aufgabe = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, holePlan(kzl));
});
var ergebnis = await warte(aufgabe);
...
If async-await does not work for some reason, use then clause:
warte(aufgabe).then(value => {
var ergebnis = value;
});

Node.js database result return late inside the function

Node.js database result return late inside the function
const db = req.app.db;
function getFeaturebyID(featureids) {
db.planFeatures.findOne({"_id": featureids }).then(features => {
return features.planFeaturesTitle;
});
}
const planLists ={};
db.planManagement.find({}).toArray((err, planList) => {
// res.end(JSON.stringify(planList));
featurearray = [];
var j =1;
planList.forEach(function(row) {
planLists._id = row._id;
features = row.planFeatures.split(',');
for (let i = 0; i < features.length; i++) {
featurearray[i] = getFeaturebyID(features[i]);
// console.log(getFeaturebyID(features[i]));
}
//row.planFeaturesName[j] = featurearray;
console.log(featurearray);
j++;
});
//console.log(planList);
// res.end(JSON.stringify(req.session));
res.render('stylist/plan_selection', {
top_results: planList,
title: 'Schedule',
config: req.app.config,
session: req.session,
message: common.clearSessionValue(req.session, 'message'),
messageType: common.clearSessionValue(req.session, 'messageType'),
helpers: req.handlebars.helpers,
showFooter: 'showFooter'
});
});
});
return features.planFeaturesTitle; return a value late while calling the function. I try callback but not works
This is due to asynchronous nature of node.js,
First declare your function async like this,
const getFeaturebyID = async (featureids) => {
const features = await db.planFeatures.findOne({"_id": featureids });
return features.planFeaturesTitle;
}
Then use it like this,
planList.forEach(async (row) => {
// your code here
for (let i = 0; i < features.length; i++) {
featurearray[i] = await getFeaturebyID(features[i]);
}
// your code here
});

node js aws lambda function

Thank you for your comments. I have written the same code in much simpler way(I think..) In the below code, the ProcessRequest is not getting called.
I am not a developer and I am trying to use lambda-nodejs to fulfill my activity.
here is the code:
function close(sessionAttributes, fulfillmentState, message) {
return {
sessionAttributes,
dialogAction: {
type: 'Close',
fulfillmentState,
message,
},
};
}
function dispatch(intentRequest, callback) {
const sessionAttributes = intentRequest.sessionAttributes;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.open('GET', "http://<server>:8086/query?db=rpt&q=select transactionName,responseTime from healthCheckTestV1 ORDER BY DESC LIMIT 9", true);
console.log("-------before SEND")
xhr.send();
console.log("AFTER SEND---------")
console.log("Inside Dispatch............")
xhr.onreadystatechange = processRequest;
function processRequest(e) {
console.log("processRequest function inside")
if (xhr.readyState == 4 && xhr.status == 200) {
var toDisplay = [];
var response = JSON.parse(xhr.responseText);
//console.log(xhr.responseText);
for (var i = 0; i < response.results.length; i++) {
for (var t = 0; t < response.results[i].series.length; t++) {
for (var j = 0; j < response.results[i].series[t].values.length; j++) {
var toSplit = response.results[i].series[t].values[j].toString() // VALUE
var splitted = toSplit.split(',');
//console.log(splitted[1]+"="+parseInt(splitted[2],10)+" seconds")
toDisplay.push(splitted[1] + "=" + parseInt(splitted[2], 10) + " seconds\n")
toDisplay.join()
//toDisplay.replace(/,/g," ")
}
console.log(toDisplay.toString().trim().replace(/,/g, " "))
}
}
}
}
callback(close(sessionAttributes, 'Fulfilled', {
'contentType': 'PlainText',
'content': `The status of your order is`
}));
}
// --------------- Main handler -----------------------
// Route the incoming request based on intent.
// The JSON body of the request is provided in the event slot.
exports.handler = (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
try {
dispatch(event,
(response) => {
callback(null, response);
});
} catch (err) {
callback(err);
}
};
But when I run the same code in eclipse, after removing the lambda handler code, it works fine.
OutPUT
-------before SEND
AFTER SEND---------
processRequest function inside
processRequest function inside
processRequest function inside
Security_Question=4 seconds
File_Download=31 seconds
View_File=11 seconds
Open_TEAM=32 seconds
File_Upload=50 seconds
Open_OneDrive=3 seconds
Logout=10 seconds
Login_OKTA=9 seconds
HomePage=5 seconds

Resources