简体   繁体   English

jQuery setTimeout如果不使用警报将无法正常工作

[英]Jquery setTimeout not working if used without alert

I am implementing this code. 我正在执行此代码。

$('.mcqtd').click(function(){
var choice = this.id;   
    checkanswer(choice,questions[x].correctAnswer);
    window.setTimeout(showquestion(x+1,0),3000); // 1 seconds
});

}

function checkanswer(answer,original){
    if (answer=='choice'+original){
        $('#choice'+original).css('backgroundColor', '#DD792E');
        $('#choice'+original).append("<span class='padding10 mcqsymbol'><img src='images/right_icon.png' /></span>");
    } else {
        $('#'+answer).css('backgroundColor', '#AFA689');
        $('#'+answer).append("<span class='padding10 mcqsymbol'><img src='images/wrong_icon.png' /></span>");
        $('#choice'+original).css('backgroundColor', '#DD792E');
        $('#choice'+original).append("<span class='padding10 mcqsymbol'><img src='images/right_icon.png' /></span>");
    }
}

Onclick , the tds should be highlighted, and after 3 seconds, the next question should be loaded but this is not happening, after 3 seconds the next question is being loaded, but backgrounds are not changing. Onclicktds应该突出显示,并且3秒钟后,应该加载下一个问题,但这没有发生,3秒钟后,正在加载下一个问题,但是背景没有改变。 If I alert something inside checkanswer() , the code works. 如果我在checkanswer()checkanswer()警报,则代码将起作用。 Any ideas what should I do? 有什么想法我该怎么办?

The to executing part must be wrapped in a anonymous function if you want to use parametes. 如果要使用参数,则to执行部分必须包装在匿名函数中。 Otherwise it is not working in setTimeout . 否则它在setTimeout不起作用。

setTimeout(function() {
    showquestion(x + 1, 0);
}, 3000);

As A.Wolff noted in the comments below, you can even pass parameters to a called function in setTimeout by extening the parameters behind the time. 正如A.Wolff在下面的注释中指出的那样,您甚至可以通过在时间后扩展参数来将参数传递给setTimeout的调用函数。

// note there are no '()' behind the function name
setTimeout(showquestion, 3000, x + 1, 0);

If you would call a function without parameters you can left out the wrapper function and the additional parameters too. 如果要调用不带参数的函数,则可以省略包装函数和其他参数。

// note there are no '()' behind the function name
setTimeout(functionWithoutParameter, 3000);

What you do is calling the function directly and passing it's return value over to setTimeout . 您要做的就是直接调用该函数,并将其返回值传递给setTimeout As you intend to use arguments with this, you will have to make use of an anonymous function , eg: 当您打算为此使用参数时,您将必须使用匿名函数 ,例如:

setTimeout(function(){ showquestion(x+1, 0);}, 3000);

Edit: 编辑:

If you only have a functioncall without arguments it woulf look like: 如果只有一个不带参数的函数调用,它将看起来像:

setTimeout("foo()", 3000);

or 要么

setTimeout(foo, 3000);

Dirtly call this in setTimeout method its not working. 在setTimeout方法中直接调用它不起作用。

  setTimeout(question, 3000);

   function question() {
     showquestion(x + 1, 0)
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM