Having trouble using JQuery .animate to animate a pattern matching algorithm. Goes through some animations too fast

I'm trying to animate a pattern matching algorithm. Depending on whether the characters of the text and pattern match or not the characters turn red or green and the pattern moves on. My problem is that the pattern moves along the text too fast not allowing enough time to show the pattern and text matching or not matching.

What would be the best way for me to try and achieve an animation where the algorithm checks if the characters match, updates the background colours then checks the next characters or moves the pattern along?

function animatePattern(boxWidth, shiftpos) {
    $("#pattern_array").animate({left: boxWidth * shiftpos});

function turnRed(x, y) {
     $(x + y).animate({backgroundColor: "#db1a35"});

function turnWhite(x, y) {
    $(x + y).animate({backgroundColor: "#fff"});

function turnGreen(x, y) {
    $(x + y).animate({backgroundColor: "#30ad03"});

function straightforward(p, t) {
    var i = 0, j = 0, k = 0;
    var boxWidth = $('#text_array .panel').outerWidth(true);
    while (j < t.length && k < p.length) {
        if (t[j]==p[k]) {
            //turn text green
            turnGreen('#t', j);
            //turn pattern green
            turnGreen('#p', k);
            //update counters to compare next characters in the pattern and text
            j = j + 1;
            k = k + 1;
        } else {
            //turn the unmatched pattern character red
            turnRed('#p', k);
            turnRed('#t', j);

            //turn all pattern white
            for (var m = 0; m < p.length; m++) {
                turnWhite('#p', m);
            //turn all text white
            for (var m = 0; m < t.length; m++) {
                turnWhite('#t', m);
            //update countes to compare the next character of text with first character of pattern
            i = i + 1;
            j = i;
            k = 0;

            //move pattern on a mismatch
            animatePattern(boxWidth, i);

jsfiddle Here you can see the animation running

Answers 1

  • You can use $.fx.speeds._default = 750; to slow down the animation, but what you are doing now seems to be queuing all the animations initially, so they are playing out of sync. What you need to do is use a setTimeout or setInterval and create a "tick" function that runs every x seconds that updates the elements.

    Some example code:

    var intervalms = 1000
    var i = 0;
    function tick() {
      if (!(i < 10)) return;
      setTimeout(tick, intervalms)

    Or using intervals

    var intervalms = 1000
    var i = 0;
    function tick() {
      if (!(i < 10)) {
    var tickInterval = setInterval(tick, intervalms);

Related Articles