笑いながらコードを書く。

vimから出たくないフロントエンドエンジニアの備忘録的な何か。

テキストをシャッフルしつつ表示する

後で見なおしてみる。

function ShuffleText(container, speed, easing) {
        this.container  = container;
        this.speed      = speed;
        this.easing     = easing;
        this.isShuffling = false;
    }
    ShuffleText.prototype.shuffle = function (targetText, endress) {
        if (this.isShuffling) {
            clearInterval(this.timerId);
        }
        this.isShuffling = true;

        var self = this,
            length = targetText.length,
            str = "",
            completeText = "",
            tempSpeed = this.speed,
            count = 0,
            timeCount = 0,
            timerId;
        timerId = setInterval(function () {
            if (!endress) {
                ++timeCount;
                if (timeCount >= tempSpeed) {
                    ++count;
                    timeCount = 0;
                    completeText = targetText.slice(0, count);

                    if (self.easing) {
                        tempSpeed += (0 - tempSpeed) / 10;
                    }
                }
            }
            str = completeText + self.getRandomText(length - count);
            self.container.innerHTML = str;

            if (count == length) {
                clearInterval(timerId);
                self.isShuffling = false;
            }
        }, 1000 / 30);
    };
    ShuffleText.prototype.getRandomText = function (length) {
        var i = 0,
            randomLength = ShuffleText.RANDOM_CHAR.length,
            str = "";
        for (; i < length; ++i) {
            str += ShuffleText.RANDOM_CHAR.charAt(~~(Math.random() * randomLength));
        }
        return str;
    };
    ShuffleText.RANDOM_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!?@#$%^&*";