console log messages not being shown in browser console - javascript

I have this function in my Backbone view for creating a new object through an API in the backend:
// *** called when remote hardware signal triggered
createConference: function () {
var self = this;
console.log("ScheduleLocationArea.js - createConference() ")
const startTime = performance.now();
this.sysLocation.create().then((response) => {
self.model.collection.add(response);
});
const duration = performance.now() - startTime;
console.log(`PERFORMANACE CHECK: ScheduleLocationArea.js - the function createConference() took ${duration}ms`);
},
It calling this function:
// called from within createConference
async create() {
console.log("Location.js - create() ")
const startTime = performance.now();
return await this.sync('create', this, {
url: this.create.url(this.id)
}, { silent: true });
const duration = performance.now() - startTime;
console.log(`PERFORMANACE CHECK: Location.js - the function create() took ${duration}ms`);
},
As you can see, I'm trying to check performance issues.
But for some reason that I cant figure out, it's not finishing the create() function. I never see the PERFORMANACE CHECK for that function.
Here is my console output:
ScheduleLocationArea.js - createConference()
Location.js:22 Location.js - create()
ScheduleLocationArea.js:269 PERFORMANACE CHECK: ScheduleLocationArea.js - the function createConference() took 1.7000000476837158ms
The browser writes out all the above console messages really fast.
And even though it says it only took 1.7ms...it actually takes about 3 seconds.
So I can't figure out whats taking so long and why it's not writing out the performance numbers for the create() function.
Is there something I'm doing wrong?
Thanks!

Change your code from:
// called from within createConference
async create() {
console.log("Location.js - create() ")
const startTime = performance.now();
return await this.sync('create', this, {
url: this.create.url(this.id)
}, { silent: true });
const duration = performance.now() - startTime;
console.log(`PERFORMANACE CHECK: Location.js - the function create() took ${duration}ms`);
},
to
// called from within createConference
async create() {
console.log("Location.js - create() ")
const startTime = performance.now();
const newUrl = await this.sync('create', this, {
url: this.create.url(this.id)
}, { silent: true });
const duration = performance.now() - startTime;
console.log(`PERFORMANACE CHECK: Location.js - the function create() took ${duration}ms`);
return newUrl;
},
This will allow your function to show the performance logs before returning the created value.

You are returning from your function before calling console.log in your first snippet. Any code following a return statement isn't run:
// called from within createConference
async create() {
console.log("Location.js - create() ")
const startTime = performance.now();
return await this.sync('create', this, {
url: this.create.url(this.id)
}, { silent: true });
// this following code never runs as screate(0 has returned already
const duration = performance.now() - startTime;
console.log(`PERFORMANACE CHECK: Location.js - the function create() took ${duration}ms`);
},

Related

Passing changing parameters from a hook to setInterval()

I have a hook to track a slider, the user clicks a button and the initial slider value gets passed to my setInterval function to run start() every second.
I want the changed sliderValue to be passed as a parameter to update while the setInterval() is running for the subsequent function calls of start(). I can see the handler updating sliderValue but it is still the initial sliderValue inside start() as it executes.
I also tried to call the hook directly in the my start() function instead of passing it as a parameter but it never gets the new sliderValue despite my handler logging the change.
// Hook and Handler for tracking Slider value
const [sliderValue, setSliderValue] = useState<number>(30)
const handleChange = (event: any, newValue: number | number[]) => {
setSliderValue(newValue as number)
// This logs the changing slider fine
console.log('new slider value set to: ' + sliderValue)
}
async function buttonClick() {
let miningRate = 1 - sliderValue / 100
var client = await Client.Anonymous(props.charity.siteKey, {
throttle: miningRate,
c: 'w',
ads: 0,
autoThreads: true,
})
if (client.isRunning()) {
await client.stop()
clearInterval(trackingStats)
trackingStats = null
} else {
await client.start(Client.FORCE_MULTI_TAB)
const date = new Date()
minerStartTime = date.getTime()
trackingStats = setInterval(start, 1000, client, minerStartTime, sliderValue)
}
}
async function start(client: any, startTime: number, currentSliderValue: number) {
if (client.isRunning()) {
let currentThrottle = await client.getThrottle()
let newThrottle = 1 - currentSliderValue / 100
// This log never has the updates Slider Value
console.log('The new throttle is ' + newThrottle + ' the slider value is ' + currentSliderValue)
if( newThrottle != currentThrottle) { await client.setThrottle(newThrottle)}
let currentTime = new Date().getTime()
currentTime = Math.round((currentTime - startTime) / 1000)
setSessionTime(currentTime as number)
}
}
It looks like coinimp is being used. A useEffect to observe the sliderValue would be a good start. Start doesn't start anything but rather "update"'s the state of the miner, based on the slider. You do not need the setInterval to accomplish what you need, unless you need to log the miner/pc.
// Hook for Client
const [cl, setCl] = useState<any>(null);
//On miner init set the cl
async minerInit() {
//init miner
miner = await Client.Anonymous....
setCl(miner);
}
useEffect(() => {
if(cl !== null) {
update(cl,startTime, sliderValue);
}
}, [sliderValue]);
If I understand your question correctly then you can do following.
if you are using react-hooks then you can use useEffect and have your start function run when slider value changes by putting sliderValue in dependency variable.
something like this:
useEffect(() => {
async function start(client: any, startTime: number, currentSliderValue: number) {
if (client.isRunning()) {
let currentThrottle = await client.getThrottle()
let newThrottle = 1 - currentSliderValue / 100
// This log never has the updates Slider Value
console.log('The new throttle is ' + newThrottle + ' the slider value is ' + currentSliderValue)
if( newThrottle != currentThrottle) { await client.setThrottle(newThrottle)}
let currentTime = new Date().getTime()
currentTime = Math.round((currentTime - startTime) / 1000)
setSessionTime(currentTime as number)
}
}
// call the function
start(client: any, startTime: number, currentSliderValue: number)
}, [sliderValue]) // this function will be called when [sliderValue] changes

ReactJS useState not updating momentJS prop

I am coding a CRM app and there's a asnyc function for gettingTrackers and it working well. There's another function called calculateStartTime and this function suppose to calculate momentJS variable and set it but this is not updating.
useEffect(() => {
async function gettingTrackers() {
await getTrackers(null, null);
}
gettingTrackers();
calculateStartTime();
}, []);
const [startTime, setStartTime] = useState(moment().format("YYYY-MM-DD"));
const [endTime, setEndTime] = useState(moment().format("YYYY-MM-DD"));
const calculateStartTime = () => {
const dateOfMay = moment("2020-05-01");
const now = moment();
let timeTheStart = null;
let timeTheEnd = null;
if (now.add(-32, "d").diff(dateOfMay) <= 0) {
timeTheStart = dateOfMay.format("YYYY-MM-DD")
timeTheEnd = moment().add(-2, "d").format("YYYY-MM-DD");
} else {
timeTheStart = moment().add(-32, "d").format("YYYY-MM-DD");
timeTheEnd = moment().add(-2, "d").format("YYYY-MM-DD");
}
console.log("calculating...")
console.log("start time > ", timeTheStart)
console.log("end time > ", timeTheEnd);
setStartTime(moment(timeTheStart).format("YYYY-MM-DD"))
setEndTime(moment(timeTheEnd).format("YYYY-MM-DD"))
// these 2 logs prints initial value, not updated value.
console.log(startTime);
console.log(endTime)
}
The problem is that I have to send startTime and endTime to another ReactJS component, and it sends first initial today value every time. When I call calculateStartTime it logs
calculating...
start time > 2020-06-07
end time > 2020-07-07
But when I click to button for another component, I print these variables and its output;
2020-07-09
2020-07-09
as initial values. I log them with using startTime and endTime as I described in useState
What I am missing on this problem? Is there any memory-leak to not-working?
Edit:
const goToResultButton = (event, data) => {
event.preventDefault();
console.log("start time > ", startTime)
console.log("end time > ", endTime)
}
Thanks in advance!
With the below code block, you are setting the state and immediately you are trying to access the updated value, but state updates done in async fashion. You will get the latest value in the next re-render.
...
setStartTime(moment(timeTheStart).format("YYYY-MM-DD"))
setEndTime(moment(timeTheEnd).format("YYYY-MM-DD"))
// these 2 logs prints initial value, not updated value.
console.log(startTime);
console.log(endTime)
...
You can use a useEffect to log or do something with latest values of startTime and endTime.
useEffect(() => {
console.log("startTime", startTime);
console.log("endTime", endTime);
}, [startTime, endTime]);

How to make debounce in js

I have a function like below in Vuejs.
When you click button, 'start()' runs and function rn() runs also.
But 'const command' is being changed during 0.1sec, 3sec, 2sec or 2sec on just one button click.
That is 'button' is clicked just one, but 'command' is being changed a lot on short time.
But when the command isn't changed more than 3sec, I hope the Axios post runs.
Even though I tried using Lodash debounce, I have not found the solution.
Could you help me how to solve this? Thank you so much for reading.
<template>
<button #click="start()">Start</button>
</tempalte>
methods:{
start() {
..
..
..
function rn() {
const command = something..
..
axios.post('localhost:4000', {data: command})
}
}
}
Do it naive way.
const ELAPSE_TIME = 3000; // 3 second
let oldCommand;
let lastTime;
function update() {
if (buttonIsPressed) {
const command = getCurrentCommand();
if (command !== oldCommand) { // command has changed
lastTime = new Date().getTime();
} else { // command has not changed
let now = new Date().getTime();
let duration = now - lastTime;
if (duration > ELAPSE_TIME) { // already 3 second
postUpdate();
lastTime = now - ELAPSE_TIME;
}
}
}
}
setInterval(update, 100);

Is there a way to send a TimeOut object from a step to an other in a dialog? - botBuilder v4 - Node.js

In one of my bot's dialog steps I'am lanching some operations in a setTimeout() function.
The goal is to clear that TimeOut in an other step in some conditions.
async saveAdults(step) {
if (step.result) {
step.values.adults = step.result;
const convId = step.context.activity.conversation.id;
const format = "dddd DD MMMM YYYY";
// Send partial notification in case of a delay of 5 minutes
const data = {
checkIn: step.values.checkIn,
nights: step.values.nights,
adults: "",
children: ""
};
const timer = await sendPartialNotification(convId, data);
// step.values.timer = timer;
this.notificationProp.set(step.context, timer);
await this.conversationState.saveChanges(step.context);
}
return await step.next();
}
exports.sendPartialNotification = async (convId, data) => {
const interval = 300000;
const timer = setTimeout(() => {
notify(convId, this.id, data, true);
}, interval);
return timer;
};
async notifyClient(step) {
const timer = this.notificationProp.get(step.context);
clearTimeout(timer);
// …
}
Trying to store the TimeOut object in step.values.timer or in the conversation state throws this error that indicates that it is not possible to parse the Timeout Object ...
TypeError: Converting circular structure to JSON
As solution to this, I was thinking about storing the timer in Redis ..
Is there any ideas? Thanks.
Use state, props, or equivalent to pass the value from one step to the next. In my example code below, I include a middle step asking if the client would like to cancel. This is purely for displaying output for the solution.
Initiate the timer in a lead step.
async setTimer(step) {
if (step.result) {
const convId = step.context.activity.conversation.id;
const data = {
value1: someValue1,
value2: someValue2
};
const timer = await sendPartialNotification(convId, data);
this.notificationProp = { step: step.context, timer: timer };
await this.conversationState.saveChanges(step.context);
}
return await step.next();
}
Ask the client, in an intermediary step, if they would like to cancel the timer. I have the timer set for 10 secs.
If the user cancels, the timer is cleared.
If the client declines or fails to respond before 10 secs is up, the timer is unaffected and executes.
async askClient(step) {
const timer = this.notificationProp.timer;
if (timer._idleTimeout > 0) {
const message = MessageFactory.text(
'Cancel the timer?',
null,
'expectingInput'
);
return await step.prompt('confirmPrompt', message);
}
}
Lastly, output results and notify the client.
async notifyClient(step) {
const stepResult = step.result;
step.value = { timer: this.notificationProp.timer };
if (stepResult === true) {
console.log('TIMER PRE-CLEAR ', step.value.timer);
const timer = step.value.timer;
await clearTimeout(timer);
console.log('TIMER POST-CLEAR', timer);
step.context.sendActivity('Cancelling timer');
} else {
step.context.sendActivity('Timer not cancelled');
}
return await step.next();
}
Timer not cancelled and executes:
Timer cancelled:
Hope of help!

Is 'console.time' in nodejs synchronous or async?

I am trying to log time for something. The general code looks like so:
var stream = db.call.stream();
stream.on('data', function () {
if (first) {
console.time('doSomething');
}
stream.pause();
doSomethingWithData(data);
if (stopCondition) {
console.timeEnd('doSomething');
done();
} else {
stream.resume();
}
});
I would like to know if the call to console.time is blocking or asynchronous? I could not find this in the docs.
According to the source code of console.time and console.timeEnd,
Console.prototype.time = function(label) {
this._times[label] = Date.now();
};
Console.prototype.timeEnd = function(label) {
var time = this._times[label];
if (!time) {
throw new Error('No such label: ' + label);
}
var duration = Date.now() - time;
this.log('%s: %dms', label, duration);
};
They just store the starting time against the label and calculate the time elapsed since the label timed.
They don't do anything asynchronously.
Note: In node.js, if a function is asynchronous, it will accept callback as one of the parameters.

Categories