How to stop setTimeInterval function manually in smartface? - smartface.io

I create a setInterval method like below, I want to stop it anytime from anywhere. By the way, that function is in a if-else statement, so I cannot access the stop function.
How can it be possible?
var intervalID = setInterval(function () {
if (flag) {
stopTimer();
Pages.Page1.Label1.text = "";
}
if (time == 0) {
stopTimer();
Pages.Page1.Label1.text = "";
Device.makeCall(callNumber.rows[0][0]);
} else
updateTime();
}, 1000);
function updateTime() {
time = time - 1;
Pages.Page1.Label1.text = time;
}
function stopTimer() {
clearInterval(intervalID);
}

Just set the flag variable to true.
flag = true;
Alternatively, i would suggest to declare your functions outside of the if / else scope .
For instance, create a timer instance with start / stop methods as such :
timer = function() {};
timer.prototype.start = function ()
{
this.timerId = setInterval(function () {
/* ... */
/* call to doWork here or simply your code */
}, 1000);
}
timer.prototype.doWork = function ()
{
// override here if you want and wall doWork in setInterval
}
timer.prototype.stop = function ()
{
clearInterval(this.timerId);
}
var t = new timer();
// start the timer
t.start();
// stop the timer
t.stop();
This way you can handle your timer as you want.

Related

Limit size of entered data in tinyMCE 5

I use tinyMCE 5 in my web site to enter data stored in a database. Therefore I need to limit the entered size, including format information, to the size of the data field. How can I prohibit the user to enter more then the allowed number of bytes, say 2000?
Best of all if I could add some information like "42/2000" on the status bar.
We had a similar requirement in our project (difference: the output should be <entered_chars>/<chars_left> instead of <entered_chars>/<max_chars>), and it ended up being a custom plugin, based on the wordcount plugin. There is some hacks in there, which could make it fail whenever tinyMCE changes, since there is no API for the statusbar in version 5 at this point of time.
But maybe you will still find it useful:
(function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var maxChars = function (editor) {
return editor.getParam('number_max_chars', 3600);
};
var applyMaxChars = function (editor) {
return editor.getParam('restrict_to_max_chars', true);
};
var Settings = {
maxChars: maxChars,
applyMaxChars: applyMaxChars
};
var global$1 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker');
var getText = function (node, schema) {
var blockElements = schema.getBlockElements();
var shortEndedElements = schema.getShortEndedElements();
var isNewline = function (node) {
return blockElements[node.nodeName] || shortEndedElements[node.nodeName];
};
var textBlocks = [];
var txt = '';
var treeWalker = new global$1(node, node);
while (node = treeWalker.next()) {
if (node.nodeType === 3) {
txt += node.data;
} else if (isNewline(node) && txt.length) {
textBlocks.push(txt);
txt = '';
}
}
if (txt.length) {
textBlocks.push(txt);
}
return textBlocks;
};
var strLen = function (str) {
return str.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, '_').length;
};
var countCharacters = function (node, schema) {
var text = getText(node, schema).join('');
return strLen(text);
};
var createBodyCounter = function (editor, count) {
return function () {
return count(editor.getBody(), editor.schema);
};
};
var createMaxCount = function (editor) {
return function () {
return Settings.maxChars(editor);
}
}
var createRestrictToMaxCount = function (editor) {
return function () {
return Settings.applyMaxChars(editor);
}
}
var get = function (editor) {
return {
getCount: createBodyCounter(editor, countCharacters),
getMaxCount: createMaxCount(editor),
getRestrictToMaxCount: createRestrictToMaxCount(editor)
};
};
var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
function isAllowedKeycode(event) {
// allow arrow keys, backspace and delete
const key = event.keyCode;
return key === 37 || key === 38 || key === 39 || key === 40 || key === 8
|| key === 46;
}
var updateCount = function (editor, api) {
editor.getContainer().getElementsByClassName(
'tox-statusbar__text-container')[0].textContent = String(
api.getCount()) + " / " + String(
Settings.maxChars(editor) - api.getCount());
};
var setup = function (editor, api, delay) {
var debouncedUpdate = global$2.debounce(function () {
return updateCount(editor, api);
}, delay);
editor.on('init', function () {
updateCount(editor, api);
global$2.setEditorTimeout(editor, function () {
editor.on('SetContent BeforeAddUndo Undo Redo keyup', debouncedUpdate);
editor.on('SetContent BeforeAddUndo Undo Redo keydown', function (e) {
if (!isAllowedKeycode(e) && Settings.applyMaxChars(editor) &&
api.getCount() >= Settings.maxChars(editor)) {
e.preventDefault();
e.stopPropagation();
}
});
}, 0);
});
};
function Plugin(delay) {
if (delay === void 0) {
delay = 300;
}
global.add('charactercount', function (editor) {
var api = get(editor);
setup(editor, api, delay);
return api;
});
}
Plugin();
}());
Currently I'm working on a preprocessor for the paste plugin, so that the max_length effects also pasted text. That's why you see the charactercount API in the code.

Flutter: Timer timer cannot end previous session with timer.cancel()?

when I call timer.cancel (), the clock stops working. But when calling back to start a new session, I discover that the _u variable in the old session still counts from itself and parallel with new one.
Please help !
startTime(60);
timer.cancel();# It worked.
timer = null;
startTime(60);# but when recall. It working with 2 session. (old and new)
//Call timer.cancel() _u variable stop at 40.
//Recall startTime() _u variable counts with 2 session (40) and (60)
startTime(reset){
int _u = reset;
const oneSec = const Duration(seconds: 1);
timer = Timer.periodic(
oneSec,
(Timer timer) => setState(
() {
if (_u < 1) {
timer.cancel();
// call my handle
} else {
_u = _u -1;
if(_u <0){
timer?.cancel();
}
}
},
),
);
Cancel the timer if it is not null. The code below was tested
void startTime(reset) {
int _u = reset;
const oneSec = const Duration(seconds: 1);
if (timer != null) {
timer.cancel();
}
timer = Timer.periodic(oneSec, (Timer t) {
if (_u < 1) {
t.cancel();
// call my handle
} else {
_u = _u - 1;
print(_u);
if (_u < 0) {
t?.cancel();
}
}
});
}

Asynchronous function in SAPUI5

I'm using a function to open a dialog in SAPUI5. While this dialog is opening, some data should be set in the local storage of the browser. However, when I add the local storage function, it takes a few seconds to open the dialog.
Is there a way I can make the local storage async? I tried putting the function of the local storage after the opening of the dialog. But it doesn't change anything..
/* WHEN THE USER CLICKS ON AN ASSIGNMENT IN THE CALENDAR */
onClickAssignment: function(oEvent) {
var oAppointment = oEvent.getParameter("appointment");
this.lastAppointment = oAppointment;
if (oAppointment) {
var key = this.byId("PC1").getViewKey();
if (key === "Month") {
if (!this._oDetailsDialog || this._oDetailsDialog === null) {
// show assignment dialog
this._oDetailsDialog = sap.ui.xmlfragment(this.fragmentDetailsId, "be.xxxxxxxxxxx.fragment.viewAssignment", this);
this.getView().addDependent(this._oDetailsDialog);
}
} else {
if (!this._oDetailsDialog || this._oDetailsDialog === null) {
// show subassignment dialog
this._oDetailsDialog = sap.ui.xmlfragment(this.fragmentDetailsId, "be.xxxxxxxxxxx.fragment.viewSubassignment", this);
this.getView().addDependent(this._oDetailsDialog);
}
}
this.oAppBC = oAppointment.getBindingContext();
this._oDetailsDialog.setBindingContext(this.oAppBC);
this._oDetailsDialog.open();
this.lastClickedAssignment = oAppointment.getProperty("assignment");
this.lastClickedSubassignment = oAppointment.getProperty("subassignment");
//SET LOCAL STORAGE
// var stringifiedContext = CircularJSON.stringify(oAppointment.getBindingContext());
// var stringifiedAssignment = CircularJSON.stringify(oAppointment.getProperty("assignment"));
// var stringifiedSubassignment = CircularJSON.stringify(oAppointment.getProperty("subassignment"));
// this.setLocalStorage("context", stringifiedContext);
// this.setLocalStorage("assignment", stringifiedAssignment);
// this.setLocalStorage("subassignment", stringifiedSubassignment);
}
},
You can detach execution of that part of the code from the main execution thread by wrapping it into setTimeout:
/* WHEN THE USER CLICKS ON AN ASSIGNMENT IN THE CALENDAR */
onClickAssignment: function(oEvent) {
var oAppointment = oEvent.getParameter("appointment");
this.lastAppointment = oAppointment;
if (oAppointment) {
var key = this.byId("PC1").getViewKey();
if (key === "Month") {
if (!this._oDetailsDialog || this._oDetailsDialog === null) {
// show assignment dialog
this._oDetailsDialog = sap.ui.xmlfragment(this.fragmentDetailsId, "be.xxxxxxxxxxx.fragment.viewAssignment", this);
this.getView().addDependent(this._oDetailsDialog);
}
} else {
if (!this._oDetailsDialog || this._oDetailsDialog === null) {
// show subassignment dialog
this._oDetailsDialog = sap.ui.xmlfragment(this.fragmentDetailsId, "be.xxxxxxxxxxx.fragment.viewSubassignment", this);
this.getView().addDependent(this._oDetailsDialog);
}
}
this.oAppBC = oAppointment.getBindingContext();
this._oDetailsDialog.setBindingContext(this.oAppBC);
this._oDetailsDialog.open();
this.lastClickedAssignment = oAppointment.getProperty("assignment");
this.lastClickedSubassignment = oAppointment.getProperty("subassignment");
setTimeout(function () {
//SET LOCAL STORAGE
var stringifiedContext = CircularJSON.stringify(oAppointment.getBindingContext());
var stringifiedAssignment = CircularJSON.stringify(oAppointment.getProperty("assignment"));
var stringifiedSubassignment = CircularJSON.stringify(oAppointment.getProperty("subassignment"));
this.setLocalStorage("context", stringifiedContext);
this.setLocalStorage("assignment", stringifiedAssignment);
this.setLocalStorage("subassignment", stringifiedSubassignment);
});
}
},
OR you can also do it after open:
this._oDetailsDialog.attachEventOnce('afterOpen', function () {
//SET LOCAL STORAGE
// ...
});

TYpescript : Static methods on Function as class

I have a fn that inherit an existing fn ( take Angular1 $q for example )
//$q original behavior
var defer = $q.defer();
defer.promise.then(function(result){})
//or
$q( (resolve, reject) => {
//promise execution here
}).then(function(result){});
If I want to decorate it, I would do :
var Qdecorator = function($delegate) {
var Q = function(resolver:any): any {
//do some extra stuff here
return $delegate.apply($delegate, arguments);
}
//Assign the static methods here:
Q.defer = function() {
//do some stuff
return $delegate.defer.apply($delegate, []);
}
//same goes for race, when, resole reject and so on
return Q;
}
Problem is that typescript complains about
Property defer, race, when, resolve, etc... does not exist on type '(resolver: any) => any'
I tried to use the IQService, and IPromise with no luck, btu I'd like to raise a more global question :
How do I define late static methods on function() that return an object without using new
I am copying pasting the answer to my question from this link:
https://www.typescriptlang.org/docs/handbook/interfaces.html
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
let counter = <Counter>function (start: number) { };
counter.interval = 123;
counter.reset = function () { };
return counter;
}
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;

why my function call many time , with bootstrap modal?

My JS :
$("#modalADDpp").on('shown',function(e){
$(this).find('input[type=text]').filter(':first').focus();
var count = 0;
alert(count);
$('#pp_tab a').click(function () {
$(this).tab('show');
})
$("#TenPP").typing({ // jquery for check when finish typing
start: function(event ,$elem) {
$(".add-on").remove();
return false;
},
stop: function (event, $elem) {
count ++;
alert(count);
if(count == 1 )
{
Ajax_Check_Name($elem);// Check name same with database by ajax
}
return false;
},
delay: 500
});
$("#modalADDpp").on('hidden',function(e){
$(this).closest('form').find("input[type=text], textarea").val("");
$(".add-on").remove();
});
});
I crate $count = 0 at my modal shown . At first time , it work ok . But when hide modal and re-open , $count not = 0 , $count now = 2 => my function will call two time and if close agains , it plus to 3 , 4 ,5 times .
I use
if(count == 1 )
because i want it run only one time .So it work ok but I dont know where is problem . Need Help !!!
Code of typing.js
(function ($) {
//--------------------
// jQuery extension
//--------------------
$.fn.typing = function (options) {
return this.each(function (i, elem) {
listenToTyping(elem, options);
});
};
//-------------------
// actual function
//-------------------
function listenToTyping(elem, options) {
// override default settings
var settings = $.extend({
start: null,
stop: null,
delay: 400
}, options);
// create other function-scope variables
var $elem = $(elem),
typing = false,
delayedCallback;
// start typing
function startTyping(event) {
if (!typing) {
// set flag and run callback
typing = true;
if (settings.start) {
settings.start(event, $elem);
}
}
}
// stop typing
function stopTyping(event, delay) {
if (typing) {
// discard previous delayed callback and create new one
clearTimeout(delayedCallback);
delayedCallback = setTimeout(function () {
// set flag and run callback
typing = false;
if (settings.stop) {
settings.stop(event, $elem);
}
}, delay >= 0 ? delay : settings.delay);
}
}
// listen to regular keypresses
$elem.keypress(startTyping);
// listen to backspace and delete presses
$elem.keydown(function (event) {
if (event.keyCode === 8 || event.keyCode === 46) {
startTyping(event);
}
});
// listen to keyups
//$elem.keyup(stopTyping);
// listen to blurs
$elem.blur(function (event) {
stopTyping(event, 0);
});
}
})(jQuery);
try to reset the count to 0 ... on hidden or in stop function ...
if(count == 1 )
{
Ajax_Check_Name($elem);// Check name same with database by ajax
count = 0;
}
Or
$("#modalADDpp").on('hidden',function(e){
$(this).closest('form').find("input[type=text], textarea").val("");
$(".add-on").remove();
count = 0;
});