简体   繁体   English

为什么回来; 不停止功能?

[英]Why return; does not stop the function?

Here is the code I simplified, but the nature of the problem is the same:下面是我简化的代码,但是问题的本质是一样的:

var counter=0;

function test(){
    window.onclick="return;";
    t.value=counter;
    counter++;
    setTimeout(test,1000);
}

t=document.createElement("textarea");
document.body.insertBefore(t, document.body.firstChild);
test();

Sets up a timer, however, as you can see, the clock does not stop (ie function exits) after I clicked the window.设置计时器,但是,如您所见,在单击窗口后时钟不会停止(即函数退出)。 So where is the problem?那么问题出在哪里呢?

Edit : The motivation of this question comes from: Early exit from function?编辑:这个问题的动机来自: 提前退出功能?

Edit^2 : Then there is noway to make 'onlick' trigger the returning value of test()?编辑^ 2 :那么就没有办法让'onlick'触发test()的返回值了吗? (ie equivalent of asking whether a function can return as its super-function) (即相当于询问一个函数是否可以作为它的超函数返回)

That function has long since exited when you're trying to call return .当您尝试调用return时,该函数早已退出。 JavaScript isn't going to throw itself into a time machine and prevent the setTimer call from being executed. JavaScript 不会将自己投入时间机器并阻止执行setTimer调用。 It's too late for that.为时已晚。

What you need to do is cancel the timer, and in order to do that you have to save a handle to it:您需要做的是取消计时器,为此您必须保存一个句柄:

var counter = 0;
var timer;

function test(){
    window.onclick = function() {
      if (timer) { clearTimeout(timer) }
    }

    t.value=counter;
    counter++;
    timer = setTimeout(test,1000);
}

Every ten minutes, you tell your wife "if you see a postman, do nothing.".每十分钟,你告诉你的妻子“如果你看到邮递员,什么都不做。”。 Unsurprisingly, when she sees a postman, she does nothing.不出所料,当她看到邮递员时,她什么也不做。

Basically, what you're doing is identical, but less secure, way of writing this:基本上,你正在做的事情是相同的,但不太安全,写这个的方式:

window.onclick = function() {
  return;
}

ie when a click is detected, it executes a function that does nothing but return.即当检测到点击时,它执行一个函数,除了返回什么都不做。 It has nothing to do with the function test .它与功能test无关。

In the statement:在声明中:

window.onclick="return;";

the string "return;"字符串"return;" is assigned to the window.onclick property, which will replace the current value (whatever that might be).分配给window.onclick属性,它将替换当前值(无论是什么)。

If your intention was to end execution of the test function, then a return statement is required:如果您的意图是结束测试函数的执行,则需要return 语句

return;

The return keyword must appear as the start of a statement, it can't be assigned. return关键字必须出现在语句的开头,不能赋值。

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

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