I try to implement a TimeSequence Array approximate access mechanism in JavaScript.
My project want to record mutable value with time-stamp on every event in an array, in time sequence manner.
Say, if the event occurs on 2014/10/05 12:59:59 001,
val[20141005125959001] = 4;
on 2014/10/05 13:00:05 234,
val[20141005130005234] = 7;
Then, later,
the code is supposed to to access val approximately with a function, that is,
getVal(20141005125959001) = 4;
getVal(20141005130005234) = 7;
and in addition, when the function access val array with unassigned index such as
val[20141005125959002] or val[201410051300000100], the smart function returns
getVal(20141005125959002) = 4 // since this is prior timing that the value is going to become 7
To implement such a function, I wonder what would be the smartest way.
An obvious simple method is scan incrementally whole array index started from the required index val, and that would work when the event is so frequent (mill second base), however, once the event is infrequent, the mill-second incremental index scan is not effective.
Probably I need to add index of index, but I would like to hear smart opinion.
Any idea? thanks.
PS
I post my own solution
See below
recording logic
var compute = function()
{
var moment = require('moment');
var utc = moment().utc();
var YY = utc.year() - 2000 + '';
var MM = utc.month() + 1 + '';
var DD = utc.date() + '';
var HH = utc.hour() + '';
var mm = utc.minute() + '';
var ss = utc.second() + '';
var msc = utc.millisecond() + '';
log(YY);
log(MM);
log(DD);
log(HH);
log(mm);
log(ss);
log(msc);
var preObj = this;
if (preObj[YY] === undefined)
{
preObj[YY] = {};
}
if (preObj[YY][MM] === undefined)
{
preObj[YY][MM] = {};
}
if (preObj[YY][MM][DD] === undefined)
{
preObj[YY][MM][DD] = {};
}
if (preObj[YY][MM][DD][HH] === undefined)
{
preObj[YY][MM][DD][HH] = {};
}
if (preObj[YY][MM][DD][HH][mm] === undefined)
{
preObj[YY][MM][DD][HH][mm] = {};
}
if (preObj[YY][MM][DD][HH][mm][ss] === undefined)
{
preObj[YY][MM][DD][HH][mm][ss] = {};
}
preObj[YY][MM][DD][HH][mm][ss][msc] = preObj.val;
};
reading logic
var value = function(utc)
{
log('--value--');
var Obj = this;
var YY = utc.year() - 2000;
var MM = utc.month() + 1;
var DD = utc.date();
var HH = utc.hour();
var mm = utc.minute();
var ss = utc.second();
var msc = utc.millisecond();
log(YY);
log(MM);
log(DD);
log(HH);
log(mm);
log(ss);
log(msc);
var iYY = YY;
while (iYY >= 0)
{
if (Obj[iYY] === undefined)
{
log('YY NOT found');
iYY--;
MM = 12;
}
else
{
log('YY found');
var iMM = MM;
while (iMM >= 1)
{
if (Obj[iYY][iMM] === undefined)
{
log('MM NOT found');
iMM--;
DD = 31;
}
else
{
log('MM found');
var iDD = DD;
while (iDD >= 1)
{
if (Obj[iYY][iMM][iDD] === undefined)
{
log('DD NOT found');
iDD--;
HH = 23;
}
else
{
log('DD found');
var iHH = HH;
while (iHH >= 0)
{
if (Obj[iYY][iMM][iDD][iHH] === undefined)
{
log('HH NOT found');
iHH--;
mm = 59;
}
else
{
log('HH found');
var imm = mm;
while (imm >= 0)
{
if (Obj[iYY][iMM][iDD][iHH][imm] === undefined)
{
log('mm NOT found');
imm--;
ss = 59;
}
else
{
log('mm found');
var iss = ss;
while (iss >= 0)
{
if (Obj[iYY][iMM][iDD][iHH][imm][iss] === undefined)
{
log('ss NOT found');
iss--;
msc = 999;
}
else
{
log('ss found');
var imsc = msc;
while (imsc >= 0)
{
log(imsc);
if (Obj[iYY][iMM][iDD][iHH][imm][iss][imsc] === undefined)
{
log('msc NOT found');
imsc--;
}
else
{
log('msc found');
return Obj[iYY][iMM][iDD][iHH][imm][iss][imsc];
}
}
iss--;
msc = 999;
}
}
imm--;
ss = 59;
}
}
iHH--;
mm = 59;
}
}
iDD--;
HH = 23;
}
}
iMM--;
DD = 31;
}
}
iYY--;
MM = 12;
}
}
return null;
};
Related
Can you please help me with how to use this function in Postman test script section?
() => {
var sleep = (sleepDuration) => {
var startTime = new Date().getTime();
while (new Date().getTime() - startTime < sleepDuration) {}
}
var sleepByAsyncDelayTime = () => {
var sleepDuration = postman.getEnvironmentVariable('asyncDelayTime') || 0;
sleep(sleepDuration);
}
var retryOnFailure = (predicate, numberOfRetrys, sleepDuration, reRouteRequestName, postmanAssertions) => {
var retryCountPerReq_key = request.name + '_retry_count';
var retryCountPerReq = pm.environment.get(retryCountPerReq_key) || 0;
var reflowCountPerReq_key = request.name + '_reflow_count';
var reflowCountPerReq = pm.environment.get(reflowCountPerReq_key) || 0;
var totalReflowCount_key = 'totalReflowCount';
var totalReflowCount = pm.environment.get(totalReflowCount_key) || 0;
var maxReflowCounter = postman.getEnvironmentVariable('maxReflowCounter') || 0;
var maxReflowCounterPerReq = postman.getEnvironmentVariable('maxReflowCounterPerReq') || 0;
function clearAndExit() {
pm.environment.unset(retryCountPerReq_key);
pm.environment.unset(reflowCountPerReq_key);
postmanAssertions();
}
function retry() {
sleep(sleepDuration);
pm.environment.set(retryCountPerReq_key, ++retryCountPerReq);
postman.setNextRequest(request.name);
}
function reFlow() {
if (totalReflowCount < maxReflowCounter && reflowCountPerReq < maxReflowCounterPerReq) {
pm.environment.unset(retryCountPerReq_key);
pm.environment.set(totalReflowCount_key, ++totalReflowCount);
pm.environment.set(reflowCountPerReq_key, ++reflowCountPerReq);
postman.setNextRequest(reRouteRequestName);
} else clearAndExit();
}
if (predicate()) clearAndExit();
else if (retryCountPerReq < numberOfRetrys) retry();
else if (reRouteRequestName != '') reFlow();
else clearAndExit();
}
return {
common: {
sleepByAsyncDelayTime,
sleep,
retryOnFailure
}
};
}
I have followed this and still unable to make assertion with retries.
I want to set this as a function and run test cases on the collection runner.
Postman / Newman retry in case of failure
You could also do it like this:
var expectedHttpStatus = 200;
var maxNumberOfTries = 3;
var sleepBetweenTries = 5000;
if (!pm.environment.get("collection_tries")) {
pm.environment.set("collection_tries", 1);
}
if ((pm.response.code != expectedHttpStatus) && (pm.environment.get("collection_tries") < maxNumberOfTries)) {
var tries = parseInt(pm.environment.get("collection_tries"), 10);
pm.environment.set("collection_tries", tries + 1);
setTimeout(function() {}, sleepBetweenTries);
postman.setNextRequest(request.name);
} else {
pm.environment.unset("collection_tries");
pm.test("Status code is " + expectedHttpStatus, function () {
pm.response.to.have.status(expectedHttpStatus);
});
// more tests here...
}
I have a function which creates values for time as I am trying to calculate them, however when I try and change a drop down times I the values don't change as they just stay at 7. The function only loads the default values (time) which is 7 as it is 7 am.
As you can see from the screenshot when the form is loaded it has a time of 7am with the value of 7, but when I change the time to 8:00 it does not show the proper value of 8 and stays at a value of 7
Here is my code:
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var timeStringToValue = function timeStringToValue(timeStr) {
var _timeStr$match = timeStr.match(/(\d+):(\d+) ([ap]m)/),
_timeStr$match2 = _slicedToArray(_timeStr$match, 4),
hours = _timeStr$match2[1],
minutes = _timeStr$match2[2],
ampm = _timeStr$match2[3];
var ampmHourModifier = ampm === 'pm' ? 12 : 0;
return Number(hours) + ampmHourModifier + minutes / 60;
};
var startMonTimeStr = $('.start-time-monday option:selected').text();
var FinishtMonTimeStr = $('.finish-time-monday option:selected').text();
var startMonValue = timeStringToValue(startMonTimeStr);
console.log(timeStringToValue(startMonTimeStr));
console.log(timeStringToValue(FinishtMonTimeStr));
How can an array value (could be any number less than 20K) be appended to a string?
I'm trying to imitate :
if (form1.EActQ20 === undefined) { Q2B0 = 0; }
else (Q2B0 = document.form1.EActQ20.value);
var und = x < 20000;
var less1 = form1.EActQ1.und.toString();
var less2 = form1.EActQ2.und.toString();
var less3 = form1.EActQ3.und.toString();
var less4 = form1.EActQ4.und.toString();
if (less1 === undefined) { Q1B.und.toString() = 0; }
else (Q1B.und.toString() = document.less1.value); /// is now a value to get added in an equation
if (less2 === undefined) { Q2B.und.toString() = 0; }
else (Q2B.und.toString() = document.less2.value);
if (less3 === undefined) { Q3B.und.toString() = 0; }
else (Q3B.und.toString() = document.less3.value);
if (less4 === undefined) { Q4B.und.toString() = 0; }
else (Q4B.und.toString() = document.less4.value);
/// Revised Code Below
arr = [];
var und = 0; // some number below 2000
var less = form1["EActQ1" + und];
if (less1 === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less1" + und].value;
}
if (less2 === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less2" + und].value;
}
if (less3 === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less3" + und].value;
}
if (less1 === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less1" + und].value;
}
add = (["Q1B"+ und] * 1)+(["Q2B"+ und] * 1)+(["Q3B"+ und] * 1)+(["Q4B"+ und] * 1);
Returns NaN. I'm defining cells based on their values and trying to add them up.
You seem to be looking for bracket notation:
var und = 0; // some number below 2000
var less = form1["EActQ" + und];
Also use an object to collect all those values, not a set of Q2B… variables. Or even better, just an array:
arr = [];
…
if (less === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less" + und].value;
}
hello all i am using the following js code to convert the input type date into three different text boxes for day,month and year.
js
(function () {
var sign = function(x) {
return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN;
};
// TODO Calcular año bisiesto
var bisiesto = function(year)
{
return true;
// return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) ? 1 : 0;
};
$.fn.insertAt = $.fn.insertAt || function(index, $parent) {
return this.each(function() {
if (index === 0) {
$parent.prepend(this);
} else {
$parent.children().eq(index - 1).after(this);
}
});
};
var Crossdp = function(e, o) {
if (e.data("cross-datepicker")) {
return this;
}
e.attr("type", "text");
o = $.extend({}, $.fn.cdp.defaults, o);
if(o.hideInput)
e.hide();
var cnt = $("<div>").addClass(o.classes.container || "").data("input", e).insertBefore(e);
// Data
var days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Read format
var d = $("<select>").addClass(o.classes.controls || "").addClass(o.classes.days || ""),
m = $("<select>").addClass(o.classes.controls || "").addClass(o.classes.months || ""),
y = $("<select>").addClass(o.classes.controls || "").addClass(o.classes.year || "");
/**
* Gets the format metadata.
*/
var getFormat = function(format) {
var f = {},
last = "",
order = 0,
elements = {
"d": d,
"m": m,
"y": y
};
for(var i = 0, of=format; i < of.length; i++) {
var c = of[i];
if(last == c) {
f[c].count ++;
}
else if(c == "d" || c == "y" || c == "m") {
f[c] = {
"count": 1,
"order": order++,
"e": elements[c]
};
elements[c].data("order", f[c].order);
last = c;
}
if(order > 3) {
throw "Invalid date format";
}
}
return f;
};
var iF = getFormat(o.inputFormat),
f = getFormat(o.format);
for(var i in f) {
f[i].e.appendTo(cnt);
}
cnt.sort(function(a, b) {
if(a.data("order") > b.data("order")) {
return 1;
}
else if(a.data("order") < b.data("order")) {
return -1;
}
else {
return 0;
}
});
// Helpers
/**
* Format a numeric day to string.
*/
var formatDay = function(day, format) {
var text = String(day),
c = format || f.d.count;
while(c > text.length) {
text = "0" + text;
}
return text;
};
/**
* Format a numeric month to string.
*/
var formatMonth = function(month, format) {
if(month > 12) {
throw "Invalid month: "+month;
}
var c = format || f.m.count,
text = String(month);
if(c == 2) {
if(text.length == 1) {
text = "0" + text;
}
}
else if(c == 3) {
text = o.months[i-1].substr(0, 3);
}
else if(c == 4) {
text = o.months[i-1];
}
else {
throw "Invalid month format";
}
return text;
};
/**
* Format a numeric month to string.
*/
var formatYear = function(year, format) {
var text = String(year),
c = format || f.y.count;
if(c == 2) {
text = text.substr(text.length-2, 2);
}
else if(c != 4) {
throw "Invalid year format";
}
return text;
};
var parseYear = function(date, format) {
// TODO
};
// Update input function
var formatDate = function(resultFormat, readFormat, years, months, days) {
var a = ["d", "m", "y"],
result = resultFormat;
if(typeof days === 'string')
days = parseInt(days);
if(typeof months === 'string')
months = parseInt(months);
if(typeof years === 'string')
years = parseInt(years);
for(var i = 0; i < a.length; i++) {
var ch = a[i], /* Example: a[0]='d' */
format = readFormat[ch], /* Example: uF['d']='dd' */
word = "",
formatted = "";
for(var j = 0; j < format.count; j++) {
word += ch;
}
if(ch == "d") {
formatted = formatDay(days, format.count);
}
else if(ch == "m") {
formatted = formatMonth(months, format.count);
}
else {
formatted = formatYear(years, format.count);
}
result = result.replace(word, formatted);
}
return result;
};
var updateInput = function() {
e.val(formatDate(o.inputFormat, iF, y.val(), m.val(), d.val()));
};
this.updateInput = function() {
updateInput();
};
var updateFromInput = function() {
// TODO
};
// Generate 3 selects
/* Days */
d.data("days", 0);
/**
* Days of determinated month.
*/
var generateDays = function(month) {
if(d.data("days") == days[month-1]) {
return;
}
var selected = parseInt(d.val() || "1");
d.html("");
if(month == 0) {
return;
}
if(o.addNullOption) {
d.append("<option value=''>"+o.nullOptionText+"</option>");
}
for(var i = 1; i <= days[month-1]; i++) {
$("<option>").attr("value", i).text(formatDay(i)).appendTo(d);
}
d.val(selected);
};
d.change(function() {
updateInput();
});
generateDays(1);
/* Months */
m.change(function() {
// Regenerate days
generateDays(parseInt($(this).val()));
updateInput();
});
if(o.addNullOption) {
m.append("<option value='0'>"+o.nullOptionText+"</option>");
}
for(var i = 1; i <= 12; i++) {
m.append("<option value='"+i+"'>"+formatMonth(i)+"</option>");
}
/* Years */
var from,
to;
if(typeof o.years[0] == 'string') {
var current = new Date().getFullYear(),
count;
if(o.years.length == 3) {
current += o.years[1];
count = o.years[2];
}
else {
count = o.years[1];
}
for(var i = current; i != current + count; i += sign(count)) {
y.append("<option value='"+i+"'>"+formatYear(i)+"</option>");
}
}
else {
for(var i = o.years[0]; i != o.years[1]; i += sign(o.years[1]-o.years[0])) {
y.append("<option value='"+i+"'>"+formatYear(i)+"</option>");
}
}
y.change(function() {
updateInput();
});
// Save
this.inputs = {
d: d,
y: y,
m: m
};
// Finish
if(e.data("initial-day")) {
$(function() {
$.fn.cdp.statics.fns.set(e, [
e.data("initial-year"),
e.data("initial-month"),
e.data("initial-day")]);
});
}
updateInput();
e.data("cross-datepicker", this);
};
$.fn.cdp = function (o, arg) {
var e = $(this);
if (e.length == 0) {
return this;
}
else if (e.length > 1) {
e.each(function () {
$(this).cdp(o);
});
return this;
}
if(!e.is("input")) {
throw "You can apply Cross-DatePicker only on an 'input' element";
}
if(typeof o === 'string') {
var st = $.fn.cdp.statics;
if(!st.fns[o]) {
console.error("Unknown function "+o);
}
st.fns[o](e, arg);
return this;
}
var cdp = new Crossdp(e, o);
return this;
}
$.fn.cdp.defaults = {
hideInput: true,
format: "d/mmm/yyyy",
inputFormat: "yyyy-mm-dd",
years: ["now", -100], // [initial year, final year] or ["now", relative years count] or ["now", relative years from, relative years count]
months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
addNullOption: false,
nullOptionText: "Select",
classes: {
container: "cdp-container",
controls: "cdp-select",
days: "cdp-d",
months: "cdp-m",
years: "cdp-y"
}
};
$.fn.cdp.statics = {
fns: {
set: function(e, arg) {
var st = $.fn.cdp.statics,
obj = e.data("cross-datepicker"),
y,m,d;
if($.isArray(arg)) {
y = arg[0];
m = arg[1];
d = arg[2];
}
else if(typeof arg === 'string') {
var array = arg.split("-");
y = parseInt(array[0]);
m = parseInt(array[1]);
d = parseInt(array[2]);
}
else {
y = arg.year || arg.y;
m = arg.month || arg.m;
d = arg.day || arg.d;
}
obj.inputs.y.val(String(y));
obj.inputs.m.val(String(m));
obj.inputs.d.val(String(d));
obj.updateInput();
}
}
};
})();
how to implement
html
<input type="date" data-initial-day="20" data-initial-year="2010" data-initial-month="64" />
<!-- Required scripts -->
<script src='https://code.jquery.com/jquery-2.1.0.min.js'></script>
<script src='../src/cross-datepicker.js'></script>
<script>
$(function() {
$("input[type='date']").cdp();
});
</script>
the problem is that the code works great when defined data-initial-year for month and day also but when i want to show the default none selected date like select day select month and select year it shows blank or 0 .
i dont know how to solve this i have tried to solve the problem by adding some text into the js file but no help .
if you can suggest me something it would be great.
The plugin code needs to check if an entry is valid before setting it.
First off, set the addNullOption to true so that a "Select" text is visible.
$(function() {
$("input[type='date']").cdp({
addNullOption : true,
nullOptionText: "Select"
});
});
Then modify the last function $.fn.cdp.statics with the "check valid" code included below (demo):
$.fn.cdp.statics = {
fns: {
set: function(e, arg) {
var st = $.fn.cdp.statics,
obj = e.data("cross-datepicker"),
y,m,d;
if($.isArray(arg)) {
y = arg[0];
m = arg[1];
d = arg[2];
}
else if(typeof arg === 'string') {
var array = arg.split("-");
y = parseInt(array[0]);
m = parseInt(array[1]);
d = parseInt(array[2]);
}
else {
y = arg.year || arg.y;
m = arg.month || arg.m;
d = arg.day || arg.d;
}
// check valid
if ( obj.inputs.y.find('option[value="' + y + '"]').length ) {
obj.inputs.y.val(String(y));
}
if ( obj.inputs.m.find('option[value="' + m + '"]').length ) {
obj.inputs.m.val(String(m));
}
if ( obj.inputs.d.find('option[value="' + d + '"]').length ) {
obj.inputs.d.val(String(d));
}
obj.updateInput();
}
}
};
To show "Select" in the other selects, I ended up adding the following code because the year select didn't have a null option:
if (o.addNullOption) {
y.append("<option value='0'>"+o.nullOptionText+"</option>");
}
and changing the "check valid" code to:
// check valid
y = obj.inputs.y.find('option[value="' + y + '"]').length ? y : 0;
obj.inputs.y.val(String(y));
m = obj.inputs.m.find('option[value="' + m + '"]').length ? m : 0;
obj.inputs.m.val(String(m));
d = obj.inputs.d.find('option[value="' + d + '"]').length ? d : 0;
obj.inputs.d.val(String(d));
Get the full code from this updated demo.
I have problem with removing a timer while it not being used anymore in javascript ?
let say we have a variable tm for the timer and set it with window.setInterval, while it still running we replace it by a new setInterval, how possible to get rid of the first setInterval ?
example code
var tm = setInterval(function(){
console.log('tm1')
}, 10);
tm = setInterval(function(){
console.log('tm2')
}, 10)
this is the real problem
motion:function(ele,cssStart,cssEnd,duration,tangent, easing,loop, complete){
if(ele==null||typeof cssEnd !== 'string') throw new TypeError();
if(!$hd.isElement(ele) || !$hd(ele).isExists()) throw new TypeError();
var validRules = /(left|top|width|color|height|background-color|margin-left|margin-right|margin-top|margin-botom|border-color|padding-left|padding-right|padding-top|border-bottom-width|border-top-width|border-left-width|border-right-width|border-bottom-color|border-top-color|border-left-color|border-right-color|padding-bottom|border-width|opacity|font-size)\s?(?=:).[^;]*(?=;?)/gim;
// filtering css input
cssEnd = cssEnd.replace(/\s{2,}|\n|\t/gim,'').replace(/\s?(:)\s?/gi,'$1').match(validRules);
cssStart = !cssStart?[]:cssStart.replace(/\s{2,}|\n|\t/gim,'').replace(/\s(:)\s/gi,'$1').match(validRules);
if(!cssEnd) throw new Error('invalid css rules, please refer to the documentation about the valid css rules for animation');
// creating properties
var _cssEnd = [],
_paused = false,
_cssStart = [],
_tm = null,
_step,
_complete = typeof complete ==='function'?complete:null,
_loop = 0,
_easing = typeof easing ==='string'?easing.match(/^easein|easeout|easeinout$/)?easing:'easein':'easein',
_tangent = typeof tangent ==='string'?tangent in hd.classes.motionTangents ? tangent:'linear':'linear';
this.ele = $hd(ele),
this.duration = isNaN(duration)?1:parseFloat(duration),
this.loop = isNaN(loop)?0:parseInt(loop),
this.isPlaying = false;
this.complete = false;
// verifying the css rules of the end point
var verify = function(cssStart, cssEnd){
for (var i = 0; i < cssEnd.length; i++) {
var colorPattern = /#[a-z0-9]+|rgba?\s?\(([0-9]{1,3}\s?,\s?)+((([0-9]+)?(\.)?([0-9]+))+)?\)/gi,
name = cssEnd[i].replace(/^([a-z0-9-]+)\s?(?=:).*/gi,'$1'),
value = cssEnd[i].replace(/^[a-z0-9-]+\s?:(.*)/gi,'$1'),
startIndex = $hd(cssStart).inspectData(name+':',false),
startValue = !startIndex.length?this.ele.getcss(name):cssStart[startIndex].replace(/^[a-z0-9-]+:(.*)/gi,'$1');
if(value=='') continue;
// parsing values
if(name.match(/color/i)){
//if color
// validate the color
if(!value.match(colorPattern)) continue;
if(value.match(/#[a-z0-9]+/ig)){
// if hex then convert to rgb
var rgb = $hd(value).hex2rgb(),
value = !rgb?null:rgb;
if(!value) continue;
}
// verifying cssStart's value
startValue = !startValue.match(colorPattern)?this.ele.getcss(name):startValue;
if(!startValue.match(colorPattern)) continue;
if(startValue.match(/#[a-z0-9]+/ig)){
// if hex then convert to rgb
var rgb = $hd(startValue).hex2rgb(),
startValue = rgb==null?null:rgb;
}
// if browser doesn't support rgba then convert the value to rgb
value = !$hd.supports.rgba && value.match(/rgba/i)?value.replace(/(.*)a\s?(\((\d{1,3},)(\d{1,3},)(\d{1,3})).*/i,'$1$2)'):value;
startValue = !$hd.supports.rgba && startValue.match(/rgba/i)?startValue.replace(/(.*)a\s?(\((\d{1,3},)(\d{1,3},)(\d{1,3})).*/i,'$1$2)'):startValue;
// compare and convert the value of both to object
var colora = value.match(/[0-9]{1,3}/g),
colorb = startValue.match(/[0-9]{1,3}/g);
if(colora.length > colorb.length){
colorb.push(this.ele.getcss('opacity'))
}else if(colorb.length>colora.length){
colora.push(colorb[colorb.length-1])
}
_cssEnd.push({
type:'color',
name:name,
value:{
r:parseInt(colora[0]),
g:parseInt(colora[1]),
b:parseInt(colora[2]),
a:colora[3]?parseFloat(colora[3]):null
}
});
_cssStart.push({
type:'color',
name:name,
value:{
r:parseInt(colorb[0]),
g:parseInt(colorb[1]),
b:parseInt(colorb[2]),
a:colorb[3]?parseFloat(colorb[3]):null
}
});
}else{
value = parseFloat(value),
startValue = parseFloat((isNaN(parseFloat(startValue))?parseFloat(this.ele.getcss(name)):startValue));
if(isNaN(value)) continue;
if(isNaN(startValue)) startValue = 0;
_cssEnd.push({
type:'unit',
name:name,
value:parseFloat(value)
});
_cssStart.push({
type:'unit',
name:name,
value:parseFloat(startValue)
});
}
}
};
verify.apply(this,[cssStart,cssEnd]);
// clearing the arguments
cssStart = complete = cssEnd = duration = tangent = loop = ele = verify = null;
if($hd(_cssEnd).isEmpty()) throw new Error('MotionClass::invalid css rules');// raise error if cssEnd is empty
var _pauseTime = 0;
this.play = function(){
if(this.isPlaying) return;
if(!this.ele.isExists() || !this.ele.visible()) {
this.stop();
return;
}
this.isPlaying = true;
_paused = false;
if( $hd(_cssEnd).inspectData('left',true,true).length||
$hd(_cssEnd).inspectData('top',true, true).length)
this.ele.css('position:absolute');
var st = new Date() - _pauseTime;
_tm = window.setInterval(function(){
if(!this.ele.isExists() || !this.ele.visible()) {
this.stop();
return;
}
var pg, delta,
timePassed = new Date() - st;
pg = timePassed / (this.duration*1000);
if (pg > 1) pg = 1;
if(_easing === 'easeout'){
delta = 1 - hd.classes.motionTangents[_tangent](1 - pg);
}else if(_easing==='easeinout'){
if (pg <= 0.5) {
// the first half of animation will easing in
delta= hd.classes.motionTangents[_tangent](2 * pg) / 2
} else {
// the rest of animation will easing out
delta= (2 - hd.classes.motionTangents[_tangent](2 * (1 - pg))) / 2
}
}else{
delta = hd.classes.motionTangents[_tangent](pg);
}
// the movement
_step.call(this,delta);
if(_paused){
window.clearInterval(_tm);
_tm=null;
_pauseTime = timePassed;
this.isPlaying = false;
return;
}
if (pg == 1) {
_pauseTime =0;
if(_loop>=this.loop){
this.complete = true;
this.stop();
if(_complete)_complete.call(null,this);
}else{
_loop++;
st = new Date(),
timePassed = new Date() - st,
pg = 0;
}
}
}.bind(this),15);
};
_step = function(delta){
var styles = '';
for(var i=0;i<_cssEnd.length;i++){
var name = _cssEnd[i].name,
svalue =_cssStart[i].value,
value = _cssEnd[i].value;
if(_cssEnd[i].type == 'color'){
styles += name+':'+(value.a !=null?'rgba(':'rgb(')
+ Math.max(Math.min(parseInt((delta * (value.r-svalue.r)) + svalue.r, 10), 255), 0) + ','
+ Math.max(Math.min(parseInt((delta * (value.g-svalue.g)) + svalue.g, 10), 255), 0) + ','
+ Math.max(Math.min(parseInt((delta * (value.b-svalue.b)) + svalue.b, 10), 255), 0)
+ (value.a ==null?'':',' + $hd(parseFloat((value.a-svalue.a)*delta+svalue.a)).round(1)) +') !important;';
}else{
styles += name+':'+ $hd(parseFloat((value-svalue)*delta+svalue)).round(2) + (name.match(/opacity/i)?'':'px')+ '!important;';
}
this.ele.css(styles);
}
};
this.stop = function(){
this.isPlaying = false;
window.clearInterval(_tm);
_tm=null;
_loop = 0;
};
this.pause = function(){
_paused = true;
};
}
this how the problems came up;
var color = 'rgba('+($(1).randomize(0,255)+',')+
($(1).randomize(0,255)+',')+
($(1).randomize(0,255)+',')+
'1)';
var bcolor = 'rgb('+($(1).randomize(0,255)+',')+
($(1).randomize(0,255)+',')+
($(1).randomize(0,255)+',')+
')';
var motion = new hd.classes.motion(box,'',('height:'+($(1).randomize(10,50))+
'px;border-color:'+bcolor+
';background-color:'+color+
';left :'+((e.x || e.clientX)-(box.rectangle().width/2))+
';top : '+((e.y || e.clientY)-(box.rectangle().height/2))+
';border-top-width:'+($(1).randomize(0,50))),
2,'circle','easeinout',1, function(e){
status.html('Idle');
});
motion.play();
while variable motion has been referenced with an motion class (animation), how possible to stop the first motion's timer if it being replaced with new motion class(animation)
Really easy! clearInterval(tm). If you call them different names, you will be able to differentiate between them.