Reputation: 5322
I've tried this all day long and haven't got it. I would like to display a string of text in some delaying fashion. For example, at first it displays "a" then waits for a second then display "ab", and then waits for a second then display "abc", so far so on ...
I use D3 to display, function slice to generate partial text string from the alphabet. I use either setTimeout or setInterval. None works. I appreciate some help. Here is my code:
<!DOCTYPE html>
<html>
<head>
<style>
text {
font: bold 48px monospace;
}
.enter {
fill: green;
}
.update {
fill: #333;
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
var width = 1000,
height = 200;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(32," + (height / 2) + ")");
function update(data) {
var text = svg.selectAll("text").data(data);
text.attr("class", "update");
text.enter().append("text")
.attr("class", "enter")
.attr("x", function(d, i) { return i * 32; })
.attr("dy", ".35em");
text.text(function(d) { return d; });
text.exit().remove();
}
// Method 1 - NOT WORKING
update(alphabet.slice(0, 1));
setTimeout(function(){},3000)
update(alphabet.slice(0, 2));
setTimeout(function(){},3000)
update(alphabet.slice(0, 3));
// ...
/*/ Method 2 - NOT WORKING
var i = 1;
setInterval(function(i) {
update(alphabet.slice(0, i));
i++;
}, 1500);
*/
</script>
</body>
</html>
Upvotes: 2
Views: 8287
Reputation: 15366
The update
calls need to be in your setTimeout
function, like:
setTimeout(function () {
update(alphabet.slice(0, 1));
}, 3000);
setTimeout
is non-blocking; after the timer is up, it executes the function passed in as an argument.
Edit: You also probably want your code to be like this, removing the update function completely (maybe you have a reason for using many separate <text>
elements?):
var label = svg.append("text");
var i = 1;
setInterval(function () {
label.text(alphabet.slice(0, i++).join(""));
}, 1500);
Upvotes: 5