如何为循环的每次迭代设置延迟 [英] How to put delay for each iteration of loop

查看:145
本文介绍了如何为循环的每次迭代设置延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个循环:

count = 0

for i in 0...9 {

    count += 1

}

我想推迟.

延迟功能:

// Delay function
func delay(_ delay:Double, closure:@escaping ()->()) {

DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)

}

.

这意味着如果我想将count每秒钟增加1,我会这样做:

This means if I want to increase count by 1 every second, I would do:

count = 0

for i in 0...9 {

    delay(1) {

        count += 1

    }

}

但是这不起作用,因为它只会延迟方括号中的代码.如何延迟实际循环?我希望延迟不再重复,直到时间过去,然后循环/代码才能再次重复.

but this doesn't work as it only delays code in brackets. How do I delay the actual loop? I would like the delay to stop from iterating until the time has passed, and then the loop/code can repeat again.

推荐答案

您当前的代码不起作用,因为您正在异步执行增量操作.这意味着for循环仍将以其正常速度运行.

Your current code doesn't work because you are doing the increment asynchronously. This means that the for loop will still run at its normal speed.

要实现所需的功能,可以使用如下计时器:

To achieve what you want, you can use a timer like this:

var count = 0
let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true){ _ in
    count += 1
    print(count)
}

如果您希望它在5次后停止,请执行以下操作:

If you want it to stop after 5 times, do this:

var count = 0
var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true){ t in
    count += 1
    print(count)
    if count >= 5 {
        t.invalidate()
    }
}

这篇关于如何为循环的每次迭代设置延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆