processor model

by Richard Hunter

HTML

<h2>Processor</h2>

<div id="clock"></div>
<ul id="instructions"></ul>

CSS

#clock {
    width : 100px;
    height : 100px;
    background : black;
    display : inline-block;
    border : solid 6px blue;
    box-shadow: 0 0 0 5px black;
}
#clock.up {
    border-left-color : red;
}
#clock.across {
    border-top-color : orange;
}
#clock.down {
    border-right-color : orange;
}
#clock.back {
    border-bottom-color :green;
}
ul {
    list-style : none;
    border-top : solid 1px black;
    width : 300px;
    float : right;
    padding : 0;
    margin : 0;
}
li {
    border-bottom : solid 1px black;
    border-left : solid 1px black;
    border-right : solid 1px black;
}
.special {
    background : yellow;
}
.programA {
    background : green;
}
.programB {
    background : pink;
}

JavaScript

var counter = 0,
    limit = 40,
    memory, 
    clock,
    cpu, 
    scheduler,
    interruptVector,
    $instructions = $('#instructions');

/**
* holds memory and handles memory management
* @constructor
*/
function Memory() {
    this.internalMemory = [];
    this.processes = {};
}

/**
*  store instructions in memory.
*  @public
*  @param {Number} pid - process id
*  @param {Array} instructions - array of instructions
*/
Memory.prototype.addMemoryBlock = function (pid, instructions) {
    this.processes[pid] = {
        firstIndex : this.internalMemory.length,
        blockSize : instructions.length
    };
    this.internalMemory = this.internalMemory.concat(instructions);
};

/**
*  retrieve instruction from memory.
*  @param {Number} pid - process id
*  @param {Number} index - virtual memory index. must be in allowed range
*  @returns {Function} instruction
*/
Memory.prototype.requestInstruction = function(pid, index) {

    var process = this.processes[pid];
    if (index > -1 && index < (process.firstIndex + process.blockSize)) {
        return this.internalMemory[process.firstIndex + index];
    } else {
        throw {
            name : 'illegal memory access'
        };
    }
};

/**
 *  CPU clock
 *  @constructor
 */
function Clock(selector) {
    this.$clock = $(selector);
    this.phase = 0;
    this.listeners = [];
}
/**
 * phases of clock
 * @static
 */
Clock.phases = ['up', 'across', 'down', 'back'];

/**
 * add listeners to be called on each phase of the clock
 * @public
 */
Clock.prototype.addListener = function (listener) {
    this.listeners.push(listener);
};

/**
 * start clock and call listeners on every phase of the clock
 * @public
 */
Clock.prototype.start = function () {

    this.id = window.setInterval((function () {

        this.phase = this.phase % 4;
        this.$clock.attr("class", Clock.phases[this.phase]);
        this.listeners.forEach(function (listener) {
            listener();
        });
        this.phase++;

   ...