setTimeout

解释:设定一个定时器,在定时到期以后执行注册的回调函数。

# 方法参数

Function callback, Number delay

callback参数说明 :回调函数

delay参数说明 : 延迟的时间,函数的调用会在该延迟之后发生,单位 ms。

# 返回值

名称 解释
number 定时器的编号。这个值可以传递给 clearTimeout 来取消该定时。

# 示例

扫码体验
重新加载
请使用百度APP扫码

# 图片示例

# 代码示例

    <view class="wrap">
        <view class="card-area">
            <view class="top-description border-bottom">
                <view>Interval</view>
                <view>{{Interval}}</view>
            </view>
            <button type="primary" bindtap="bindSetInterval">setInterval</button>
            <button type="primary" bindtap="bindClearInterval">clearInterval</button>
        </view>
        <view class="card-area">
            <view class="top-description border-bottom">
                <view>timeout</view>
                <view>{{timeout}}</view>
            </view>
            <button type="primary" bindtap="bindSetTimeout">setTimeout</button>
            <button type="primary" bindtap="bindClearTimeout">clearTimeout</button>
        </view>
    </view>
    
    Page({
        data: {
            Interval: 0,
            timeout: 0
        },
        bindSetTimeout() {
            this.timeout && clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
                swan.showToast({
                    title: 'timeout',
                    icon: 'none'
                });
                this.setData({
                    timeout: 3
                })
            }, 3000);
        },
        bindClearTimeout() {
            this.timeout && clearTimeout(this.timeout);
            this.setData({
                timeout: 0
            })
        },
        bindSetInterval() {
            this.interval && clearInterval(this.interval);
            this.interval = setInterval(() => {
                swan.showToast({
                    title: 'setInterval',
                    icon: 'none'
                });
                this.data.Interval += 3;
                this.setData({
                    Interval: this.data.Interval
                })
            }, 3000);
        },
        bindClearInterval() {
            this.interval && clearInterval(this.interval);
            this.setData({
                Interval: 0
            })
        }
    });