Author Archives: donyd

Simple JavaScript Timer: Part III

The remaining requirements from the last session are:

  • Refactoring the two buttons to just one for starting/stopping the timer
  • Being able to capture snapshots of the timer countdown on a button press.
  • Clearing the snapshots and resetting the timer on another button press.

Refactoring the two buttons to a single one which would handle the starting and stopping of the timer proved to be tricky. For the single buttons Start and Stop a reference to the calling object itself was passed to the function and based on the innerHTML of that object, the button, the code would start or stop the timer.

Button innerHTML with JavaScript

JavaScript code to specify which button is being clicked

When only one button was present, there was nothing that could be used to identify what ‘state’ the timer, by extension the button, was in. Tried one or two ways to sort this but most of them resulted in the single button functioning once to start/stop the timer but after that it wouldn’t function at all.

What finally did it was the creation of a Boolean to keep tabs of whether the button was clicked. Simple but boy did it take some time getting to it. [see commit]

JavaScript button handler code

JavaScript button handler

With that out of the way the only thing left to do was to capture the counter values and show them beneath the actual counter and reset the captured values and timer count. This was simple enough and only required adding to the innerHTML of the display area and clearing them. [see commit]

One final item remaining was to enable key presses to activate the same functions as the button presses. These were:

  • ‘s’ to start and stop the timer
  • ‘t’ to record the times
  • ‘r’ reset the recorded times and timer

This presented some challenges as I wasn’t too sure how the code would be invoked from a separate script file. I thought it would have to go in the actual HTML document. But referring to the document element from the script file and adding an event listener to it did the trick.

Document event listener setup

Document event listener setup

From there it was just a simple callback function, part of which can be see above, with the event object passed to it from which the keypresses could be retrieved.

And there you have it, another successful simple  project completed. You can see it in action here https://donyd.github.io/Simple-Timer/

There was one final issue, this time with Github. You can see the code at various iterations of the work in progress, however the final Github page only shows the final results.

Catch up with the initial posts about this piece:

 

JavaScript callback functions

Another primer, this time on callback functions.  Call back functions are basically a function that is passed as an argument, or included wholly as in the case of anonymous functions, in another function’s call. It hails from, wait for it… functional programming.

One way of understanding how callbacks function *pardon the pun*, is based on one form of creating a function in JavaScript:

var someFunction = function functionName() {  // code goes here}

This is known as a function expression, whereby a function is declared and assigned to a variable. [1] Now, someFunction can be used to invoke functionName() just by calling it similarly to how a function would be called i.e. someFunction();

In a callback function pattern, in one scenario, a named function which has already been declared is passed as an argument in another function.

function gradeBoost(x){ // call back function
   return x += (x *= .15);
}

function bonusQuestion(receivedMarks, callback){ // uses callback function
  return callback(receivedMarks);
}

var finalMarks = bonusQuestion(45, gradeBoost));
console.log(finalMarks);

So, in the example above, gradeBoost is the callback function. In bonusQuestion, the second argument ‘callback’ is set to receive (be assigned) the callback function, gradeBoost, similar to the first code explanation block above this example.

Within the body of bonusQuestion, the assigned function is setup based on the parameter list of the gradeBoost callback function. The result being when bonusQuestion is called and passed in gradeBoost as the callback function argument, gradeBoost returns the result of the calculation to the bonusQuestion function call.

This is in essence how callbacks are cast and called. For some more applications of callback functions see the post on Asynchronous JavaScript.

Handy little methods for Xrm.Page calls in browser for Dynamics CRM

Based on the last post about retrieving Microsoft Dynamics CRM record based information from the console ‘Dynamics CRM – Access GUID from the browser console‘, I thought I write up some other useful bits that can be used to get information in a pinch.

Most of these have be run from the viewport where the record in question is open, unless otherwise stated.

Get an entity’s origin

frames[1].Xrm.Page.data.entity.getEntityName();

This is particularly handy when you want to know the logical name to work with programmatically. All this without having to open up the solution or form and plow through a few forms and several clicks.

Get logical name for controls in the controls collection

frames[1].Xrm.Page.getControl(0).getName();

The controls collection is a child of the ui object, which itself is a child of the Xrm.Page object. [See the visual layout on MSDN]. The index allows retrieval of control items as they occur on the form.

Get logical name for control based on display name

frames[1].Xrm.Page.getControl(0).setFocus();

Now there are no direct method calls, that I found or aware of, that could get you the logical name for a field based on its display name. Which is a big shame because that would be a very useful one.

Now this might be somewhat tedious based on what wants to be achieved, and most definitely based on the number of fields on the form, as the user will have to randomly call the setFocus() method on a guess of where the control might be in the index based on position i.e. if the field is placed in the middle of the list of fields, chances are the index will be roughly half of the length of the count of fields.

But once the focus reveals the field that the user is interested in, the previous method getName() can be used to retrieve the logical name using that same index.

Conclusion

These calls are part of the Xrm.Page model which can be referred to on the MSDN site. However, they can be utilized for quick little views at relevant information via the browser’s console.

JavaScript: Asynchronous Programming Primer

Some aspects of JavaScript are well known, or well loathed, mostly because it’s only partially understood. Some of these include that JavaScript is an interpreted language, which is not entirely true, which we’ll save for another day. Another is that JavaScript is a single threaded language, which is true but there are structures which allow more than a single thread to operate.

A city called asynchroni… city

Asynchronous programming allows multi-threading via Web API’s (such as event handlers) that handles processes and return tasks to the browser separately from the main thread.

The cycle follows that when a function or other code is encountered, it is placed on the Call Stack and the stack at this point is unavailable till this code is executed. The Call Stack is the data structure that handles function calls in the order that they were executed, i.e. first in, last out. This stack is the main thread that JavaScript runs on in browser. If, however, an asynchronous function is encountered, the code is deferred to a non Call Stack process to handle,

These other processes run the code, which are sent to it as callback functions, whose results are then queued in the Event Queue. This is eventually passed back to the Call Stack when it is empty. A common Web API that processes such asynchronous calls are Timers, these include:

setTimeout()

The setTimeout() method can be used to put a task on the event queue.  The method takes a callback function as the first argument and the amount of time to wait as the second argument. The time value is numeric in milliseconds. e.g. 500, 1000 which equates to half and one full second,

setInterval()

This is similar to the setTimetout() method however, the call back function will be called non-stop after each time value period lapses.

Stopping Timers

Each method above can be stopped using the related stopping methods:

  • clearTimeout()  // for setTimeout()
  • clearInterval()   // for setInterval()

When the respective timer events are created, it returns a numeric id which can be stored in a variable and then passed on to the methods indicated. This allows targeting a specific timer instance to be stopped.

Conclusion

Asynchronous programming allows processes, which would otherwise tie up the browser and make it unusable to another handler and return the results to the main thread. Thus allowing the application question to be efficient and responsive.

This is just a small primer on the asynchronous capabilities of JavaScript on the browser side. Stay tuned as more write ups will focus on this topic and related areas.

Simple JavaScript Timer: Part II

In the last part, of ‘Simple JavaScript Timer: Part I’, the asynchronous function was running as soon as the page was loaded. A few reasons why I assumed this was happening:

  • Since there were no synchronous calls, there was nothing on the call stack and therefore it just ran
  • Maybe some sort of mechanism was needed to prevent this from occurring

However, the real reason was that I’d invoked the setInterval() function and assigned it’s return to a variable (erroneously thinking I’d created a named function by assigning an anonymous function to a variable, which was contained within the setInterval()). So the asynchronous setInterval() was running when the script loaded and updated the innerHTML of the element it was attached to. [see commit]

This was sorted by enclosing the setInterval call within a function and then invoking that on the button’s onclick event. [see commit] The next item was to stop the timer once it was started. But that had its own issue in that the timer would not stop. Turned out that the id returned by the setInterval function was scoped to the first conditional branch and would not transfer over to the second conditional:

Asynchronous JavaScript: setInterval and clearInterval

Asynchronous JavaScript: setInterval & clearInterval

Placing the variable outside the conditionals, but still within the function body, resulted in the same thing. The variable had to be declared outside the function’s scope – read more about scope here – as declaring the variable without the var keyword still does not set its scope to global. The latest commit with all the issue fixes can be found in this commit [see commit].

So that still leaves the two outstanding requirements from the first post, as well as a new one (which is just to refactor the two buttons to just one for starting and stopping the timer):

  • Being able to capture snapshots of the timer countdown on a button press.
  • Clearing the snapshots and resetting the timer on another button press.

Those and the final wrap up can be seen in this post: Simple JavaScript Timer Part III
See the demo in action on the Github page here: https://donyd.github.io/Simple-Timer/

 

Simple JavaScript Timer: Part I

Ok following along the heels of the last mini project run down ‘Binary to Decimal Convertor‘ is a JavaScript Timer.

This project will borrow items and techniques learned from that excursion, one of which is how to showcase the various stages of the development process that shaped it. To that end, instead of codepen.io, github pages will be used. For the moment the source files can be found here: https://github.com/donyd/Simple-Timer and the commits will show the various stages involved as the project progresses.

Observances

  • So the same thing that tripped me up in the the Binary to Decimal Convertor happened here – I was trying to push a value into an HTML element instead of using the innerHTML property.
  • I’ve wired up a function timeElapsed to the onclick event of a button, however it seems to be running when the page is loaded.

So the next order of business is to correct the issue so the function is only triggered on the onclick event of the button it is attached to as well as the following:

  • Being able to capture snapshots of the timer countdown on a button press.
  • Clearing the snapshots and resetting the timer on another button press.

JavaScript binary to decimal application (Part Three): The Flux Capa… Convertor

Ok been on a hiatus due to work/college and most importantly my first born. So after a much waited delay, here’s the final piece – the actual conversion from Binary to Decimal.

This is the logic, which I took adapted from my Java lectures.

var convertToDecimal = function(binVal){
  var result = 0;
  var n = binVal.length - 1;
  for (i = 0; i < binVal.length; i++){
    var digit = binVal.charAt(i);
    result = result + (digit * Math.pow(2, n));
    n--;
  }
  return result;
}

This takes over from the last check, where we verified if an input was binary, and traverses the length of that input from left to right. Simultaneously var n is set to the positional power of the digit iterated over and added to the digit. The end result of all such additions is the decimal value.

Niggles encountered

I initially set the for loop check as n + 1; I erroneously assumed that since n was length minus one that would make up for the discrepancy, however each iteration would affect the value of n with the decrement (n–) and then the check would add 1 to it. I haven’t checked the full ramification of such a value but it did throw off conversion.

Another snag was that I was trying to set the output field’s value inside a conditional branch i.e.

if (value does not contain 1 or 0){  
  document.getElementById("output").value = input;
} else {
  /* code to execute if input is binary */
}

This was before, when I was doing a test to see output of invalid characters; input is the parameter passed to the function which contains the above conditional. That didn’t actually set the output as I’d expected. It somewhat makes sense when the function call is made – it is set to pass a value back, which expects a returned value.

document.getElementById("output").value = checkInput(binInput);

The line above can be taken to mean it would set it directly but wasn’t doing anything.

Closing Thoughts

So that pretty much wraps up the project in terms of the functionality and what was set out initially :

  • Creating a HTML/CSS/Javascript implementation of a problem we had to solve in a Java class – given a binary value, convert it to its decimal counterpart.
    • logic for the binary to decimal conversion.
    • restricting the entry value to 1’s and 0’s, probably using regular expression.

Further enhancements might be conducted to improve the user interface. One thing that came up during the exercise is that CodePen isn’t ideal for showing the various stages of the project. So each blog entry detailing the steps I’d taken will all point to the end result and not what it was like at that moment in time. Suppose that’s another issue to contend with if items are being created on CodePen. For the moment here is the completed, albeit unpolished, piece:

See the Pen
Binary to Decimal Conversion
by Donal D’silva (@donyd)
on CodePen.

JavaScript binary to decimal application (Part Two): Regular Expressions

Continuing on from the previous post, where I set up a pen on codepen.io to create a simple application that would take a binary number and covert to decimal. I’d laid out front end and the two tasks I had left were:

  • logic for the binary to decimal conversion.
  • restricting the entry value to 1’s and 0’s, probably using regular expression.

Filtering binary values using Regex

The one currently on my to do list is limit only binary values being entered into the input field. First hurdle was being able to compare the value input. Regex was my go to choice and was simple enough:

/[10]/g  -- pretty much translates to a range of digits from 1 to 0

However, there were a range of issues:

  • I assumed that even though the expression would find all instances of the pattern, it wasn’t working properly and I would have to create code to iterate through each character in the input [turned out I was using the wrong regex object methods i.e. match instead of test]
  • After finding the right method call ‘regex.test()’ the condition was picking some input which wasn’t binary.

My condition was

if (value contains 1 or 0) {
     /* code to execute if input is binary */
} else {
    /* code to execute if input isn't binary */
}

Any values which contained either a ‘1’ or ‘0’ would be accurately considered as binary figures. However, the issue was when a non valid input contained either of the valid elements ‘1’ or ‘0’ e.g. 10A, that would be considered binary as well.

I’d searched for numerous forums tips on pattern matching what was needed and excluding others i.e. show me only cases where it’s 1’s and 0’s and excluded everything else. Pretty sure there are ways but none that I could find.

Solution

The solution was very simple however, by seeking a pattern that considered everything except 1’s and 0’s and then using that as the filter to discount all non valid binary  input meant that the remaining items would surely be binary values.

if (value does not contain 1 or 0){  
  /* code to execute if not binary */
} else {
  /* code to execute if input is binary */
}

See the Pen xELLJP by Donal D’silva (@donyd) on CodePen.

Closing thoughts

The task was deceptively simple, even though it proved somewhat daunting in the beginning. Further excursions into Regex is warranted, just to get beyond the basic pattern matching that can be done. So with that we’re one step closer to the end goal.

JavaScript binary to decimal application (Part One): Getting Started

Following on the heels of the last blog “Enter your destiny here – Javascript binary to decimal“, this entry will pickup and start on the tasks for creating what was set out – creating a web application, of sorts, to convert a binary entry to decimal representation.

Firstly, a place to develop and host it. Codepen.io is my go to choice. Now this is almost ad-hoc and not planned out or scoped (I guess more software engineering principles will be focused later down the line).

First Steps

  1. The first stab involved setting up an HTML front end with a minimal of styling with CSS. It consists of two input boxes and a button.
  2. Then I changed the text styling from something other than default.
  3. I experimented with getting and setting the text boxes values with JavaScript.
  4. Then once those were working I putting them into a function.
  5. This function was then called on the onclick property of the button.

So this basically allows text to be entered into one input box and clicking on the button will push it to the other one.

See the Pen
Binary to Decimal Conversion
by Donal D’silva (@donyd)
on CodePen.

It’s nowhere near completion but not too shabby for rabid typing in between a lecture (Java of all classes).  So this will be the first iteration and more soon to follow, including:

  • logic for the binary to decimal conversion.
  • restricting the entry value to 1’s and 0’s, probably using regular expression.

Closing thoughts and caveats

One constant internal nag that I had was that the html elements weren’t entirely up to standards. I just essentially cobbled together items from memory and out of necessity i.e. I need a text box, just get it in and enter a non semantic, untagged text as its label.

Also I initially had an issue with the JavaScript (I’ve not had the best of experiences wiring up JavaScript with HTML contained in a browser before). Especially with event handlers, of which, I’m assuming, the onclick is one (see shows how much I don’t know). Which lead me to believe that I’d done it again. However, the issue was that I was trying to push the value of an input box into an HTML element.

I’d created an empty paragraph <p></p> to which I added an Id and then tried to push the value into that empty paragraph. It’s only later that I realised that I would’ve had need to affect the innerHTML property for an element like paragraph. It works fine with the input fields, as it does have a value property that can be updated with an getElementById train.