-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtyping.js
115 lines (93 loc) · 3.01 KB
/
typing.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
(function (exports) {
'use strict';
var Typing = function (element, options) {
// secure mode in case of forgetting to write 'new'
if (!(this instanceof Typing)) {
return new Typing(element, options);
} else {
this.el = element;
this.opts = options;
}
};
// construct queue for functions, context and arguments
var fnQueue = [],
contextQueue = [],
argsQueue = [],
isRunning = false;
function enQueue(fn, context, args) {
fnQueue.push(fn);
contextQueue.push(context);
argsQueue.push(args);
if (!isRunning) {
isRunning = true;
coreFunction();
}
}
// excute functions
function coreFunction() {
if (fnQueue.length) {
fnQueue.shift().apply(contextQueue.shift(), [].concat(argsQueue.shift()));
}
}
// protected functions
function getRandomSpeed(speed) {
return Math.floor(Math.random() * speed);
}
function _add(toAddText) {
var self = this,
realSpeed = self.opts.speed || 100,
toAddChar;
(function addChar() {
setTimeout(function () {
var randomSpeed = getRandomSpeed(self.opts.speed);
realSpeed = self.opts.isRandomSpeed ? randomSpeed : self.opts.speed;
if (toAddText.length) {
toAddChar = toAddText.charAt(0);
self.el.textContent = self.el.textContent + toAddChar;
toAddText = toAddText.substring(1);
addChar();
} else {
coreFunction();
}
}, realSpeed);
})();
}
function _delete(deleteLength) {
var self = this,
realSpeed = self.opts.speed || 100;
(function deleteChar() {
setTimeout(function () {
var randomSpeed = getRandomSpeed(self.opts.speed),
nowText = self.el.textContent;
realSpeed = self.opts.isRandomSpeed ? randomSpeed : self.opts.speed;
if (deleteLength) {
self.el.textContent = nowText.substring(0, nowText.length - 1);
deleteChar();
deleteLength = deleteLength - 1;
} else {
coreFunction();
}
}, realSpeed);
})();
}
function _pause(pauseTime) {
setTimeout(coreFunction, pauseTime);
}
// exposed functions
Typing.prototype = {
add: function (toAddText) {
enQueue(_add, this, toAddText);
return this;
},
delete: function (deleteLength) {
enQueue(_delete, this, deleteLength);
return this;
},
pause: function (pauseTime) {
enQueue(_pause, this, pauseTime);
return this;
}
};
// mount Typing on global object
exports.Typing = Typing;
})(window);