在执行下一行之前等待5秒 [英] Wait 5 seconds before executing next line

查看:366
本文介绍了在执行下一行之前等待5秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的这个功能不能像我想要的那样工作;作为一个JS新手我无法弄清楚为什么。

This function below doesn’t work like I want it to; being a JS novice I can’t figure out why.

我需要它等待5秒才能检查 newState -1

I need it to wait 5 seconds before checking whether the newState is -1.

目前,它不会等待,它只是立即检查。

Currently, it doesn’t wait, it just checks straight away.

function stateChange(newState) {
  setTimeout('', 5000);

  if(newState == -1) {
    alert('VIDEO HAS STOPPED');
  }
}


推荐答案

你必须将您的代码放入您提供给 setTimeout 的回调函数中:

You have to put your code in the callback function you supply to setTimeout:

function stateChange(newState) {
    setTimeout(function () {
        if (newState == -1) {
            alert('VIDEO HAS STOPPED');
        }
    }, 5000);
}

任何其他代码将立即执行。

Any other code will execute immediately.

这篇关于在执行下一行之前等待5秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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