Iterating with delay in Framer

192 Views Asked by At

I have a text field where I want to push out one word at a time. The words are in an array. The delay between words to displayed is set to 1 sec. The first word is shown 2 sec. Hence the weird double statements.

msgArray = [
    ["Hello", "World"], 
    ["89:23", "Tom Eriksen","Scooores!!"],
    ["Overtime", "about to", "start"]]

printMessageLoop =  (msgArray, target) ->
target.text = msgArray[0]
timeToRead = 1
Utils.delay timeToRead, () ->
    for i in [1..msgArray.length-1]
        Utils.delay timeToRead*i,() ->
            target.text = msgArray[i]
            print "i="+i #debugging purpose

When I call printMessageLoop(msgArray[2]) the target displays the first word correctly, but two last is "undefined". The printout says:

printMessageLoop(msgArray[2])

»i=3
»i=3

It seems like when the line target.text = msgArray[i] is executed that i is set to the last i. That is i++ = 3

Why? And how do I get around it?

1

There are 1 best solutions below

0
On

call do (i) -> before the delay to make sure the current value of i is forwarded into future instructions

printMessageLoop =  (msgArray, target) ->
target.text = msgArray[0]
timeToRead = target.text.length/20 * readingSpeed
Utils.delay timeToRead, () ->
    for i in [1..msgArray.length-1]
        do (i) ->
            Utils.delay timeToRead*i,() ->
                target.text = msgArray[i    ]
                print "i="+i
                timeToRead = target.text.length/20 * readingSpeed