« Back to full topics list
0
0

I need to determine if a script has been called again within a few seconds of the last call.

I coded up a short test that saves the last timestamp in a storage.global variable (which could actually be a storage.local variable) and then compares the current time to that saved value to see if enough time has elapsed. When it exits, it saves the current timestamp for the next run.

Problem is, even though within the script it maintains the current time in the storage.global variable, when the script exist the new time isn’t saved!

Here’s the code. Seems like when exiting, the variable storage.global.LastInstance doesn’t get updated.

curTime = new Date().getTime();
 if (storage.global.LastInstance != null) {
 console.info("not null");
 oldTime = storage.global.LastInstance;
 if (curTime > (storage.global.LastInstance+10000)) {
 console.info("OK to proceed");
 }
 else {
 console.info("too soon");
 }
 console.info("oldTime " + oldTime/1000);
 console.info("Last Instance " + storage.global.LastInstance/1000);
 console.info("curTime " + curTime/1000);
 }
 else {
 console.info("it is null");
 }
 storage.global.LastInstance = curTime;
 console.info("Last Instance " + storage.global.LastInstance/1000);
 return 0;

Is there something I’m missing about when global variables do and don’t get saved. I’ve been working with Scriptr for several months now and have never seen this kind of behavior.

ANSWERED
Marked as spam
Posted by - Asked on October 4, 2018 9:51 pm - 62 views

1 Replies

0
Private reply

Hi Ira,

The issue you're facing is due to the float precision. In other words, when you save a float it's going to lose its precision, so next time you read it, it won't look the same. And when you're saving a timestamp in storage it gets saved as a float, that's why you're seeing this issue.

I modified your script adding the .toString() function to save it as a string in storage, then used the Number() function to convert it back to numeric after it's read so you can perform your operations, and it worked:

curTime = new Date().getTime();

if (storage.global.LastInstance != null) {
	console.info("not null");
	
	oldTime = Number(storage.global.LastInstance);
	if (curTime > (Number(storage.global.LastInstance) + 10000)) {
		console.info("OK to proceed");
	} else {
		console.info("too soon");
	}
	
	console.info("oldTime " + oldTime / 1000);
	console.info("Last Instance " + Number(storage.global.LastInstance) / 1000);
	console.info("curTime " + curTime / 1000);
} else {
	console.info("it is null");
}

storage.global.LastInstance = curTime.toString();
console.info("Last Instance " + Number(storage.global.LastInstance) / 1000);

return 0;

I hope this helps.

Julien

Marked as spam
Posted by - Replied on October 5, 2018 11:16 am

It definitely does help. Thanks for the answer and taking the time to provide a solution.

( at October 5, 2018 2:37 pm)