首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript,setTimeout

JavaScript,setTimeout
EN

Stack Overflow用户
提问于 2018-10-19 14:16:18
回答 2查看 147关注 0票数 1

我必须在我的网页上创建一个输入类型的文本表单来修改一个setTimeout值,这个值是根据用户在我的javascript代码中的输入来修改的。我能做到吗?如果我能做到的话,我怎么做?

我厌倦了从用户输入向后端发送一个字符串,而不是使用ajax调用,将字符串分配给javascript中的一个变量,但由于内部html是一个字符串,所以它不能工作,而且当我将它转换为int时,它也不工作。

代码语言:javascript
复制
function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       document.getElementById("idovalt").innerHTML =
       this.responseText;
    }
  };
  xhttp.open("GET", "toltes", true);
  xhttp.send();
}

这是一个输入表单:

var idovalt = 1000;

setTimeout(function(){ize()}, idovalt);

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-10-19 14:39:45

字符串或整数与问题无关。

HTML:

代码语言:javascript
复制
<input type="text" id="idovalt" value="1000">

联署材料:

代码语言:javascript
复制
function ize() {
  // do something
}

setTimeout(ize, document.getElementById('idovalt').value);

如果您想直接为setTimeout()的第一个参数编写一些代码,则应该引用该代码。

例如,

代码语言:javascript
复制
setTimeout('alert("Hello!")', 1000);
票数 0
EN

Stack Overflow用户

发布于 2018-10-19 14:40:47

是的可以解决这个问题,我将使用Jquery来处理事件,但当然可能会改变它。

代码语言:javascript
复制
var myInput = $("#timeoutDelay"),
    timeOut = null;


function setTimeOutOnInputChange(timeout) {
    timeOut = setTimeout(function () {
        console.log("Your code...");
        //Ize();
    }, timeout);
}

// I did not get why you are doing this, asynchronous call execute after the timeout function, thats why you need to wait until is ready to change de timeout, in case time out value comes from server and not for user input, otherwise it doesn't makes sense.
function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       document.getElementById("idovalt").innerHTML = this.responseText;
       setTimeOutOnInputChange(parseInt(this.responseText)); // Assuming does not return an object
    }
  };
  xhttp.open("GET", "toltes", true);
  xhttp.send();
} 


myInput.change(function () {
    var val = this.value;
    if (timeOut != null) {
        clearTimeout(timeOut);
    }

    if (isNaN(val)) {
        console.error("Input is not a number");
    } else {
        setTimeOutOnInputChange(val);
    }    
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52894218

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档