“用户正在输入”功能在聊天中

时间:2022-06-07 03:42:41

I'm trying to add in chat a "user is typing" function; chat written in PHP + MySQL/Ajax.

我想添加一个聊天“用户正在输入”功能;用PHP + MySQL/Ajax编写的聊天。

How it should work:

它应该是如何工作的:

-when my chat partner X starts typing I see in my chat box: "X is typing"

当我的聊天伙伴X开始打字时,我在我的聊天框里看到:“X在打字”

-when I (named Y) am typing he sees in his chat box: "Y is typing" (just like Yahoo Messenger).

-当我(名为Y)输入时,他在他的聊天框里看到:“Y正在输入”(就像Yahoo Messenger一样)。

The code I've tried so far:

我尝试过的代码:

<script type="text/javascript" language="javascript">
    var timer = 0;

    function reduceTimer() {
        timer = timer - 1;
        isTyping(true);
    }

    function isTyping(val) {
        if (val == 'true') {
            document.getElementById('typing_on').innerHTML = "User is typing...";
        } else {

            if (timer <= 0) {
                document.getElementById('typing_on').innerHTML = "No one is typing -blank space.";
            } else {
                setTimeout("reduceTimer();", 500);
            }
        }
    }
</script>

<label>
    <textarea onkeypress="isTyping('true'); timer=5;" onkeyup="isTyping('false')" name="textarea" id="textarea" cols="45" rows="5"></textarea>
</label>
<div id="typing_on">No one is typing -blank speace.</div>

Questions:

问题:

  1. If I stop for a few seconds to think about my spelling it looks like I've stopped typing. Is there a more relevant and less complicated way to set this function? Is there possible a code for:

    如果我停下来思考一下我的拼写,看起来我已经停止打字了。是否有更相关更简单的方法来设置这个函数?是否可能有以下代码:

    • text box not empty (user pressed any key so started typing) -> Message: User is typing.
    • 文本框不为空(用户按下任何键开始输入)->消息:用户正在输入。
    • text box empty -> Message: User is not typing.
    • 文本框空->消息:用户没有输入。
    • text box not empty, but user hasn't pressed any key for longer than 5 seconds -> Message: User is not typing.
    • 文本框不是空的,但是用户没有按任何键超过5秒->消息:用户没有输入。
  2. It shows to myself that I am typing; how could I implement it or where, in order to see in my chat box the "X user is typing" and not "Myself is typing". Same for the other user, he should get a message about me typing/not typing , not about himself.

    它向我自己表明我在打字;我如何实现它,或者在哪里,为了在我的聊天框中看到“X用户正在输入”而不是“我自己在输入”。对另一个用户来说也是一样,他应该得到关于我打字/不打字的信息,而不是关于他自己的信息。

Thank you.

谢谢你!

4 个解决方案

#1


9  

I have created a fiddle that might be helpful to you. The idea is to refresh activity message using javascript setInterval function.

我发明了一种可能对你有帮助的小提琴。其思想是使用javascript setInterval函数刷新活动消息。

var textarea = $('#textarea');
var typingStatus = $('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970, actually some time in the past
var typingDelayMillis = 5000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message

function refreshTypingStatus() {
    if (!textarea.is(':focus') || textarea.val() == '' || new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
        typingStatus.html('No one is typing -blank space.');
    } else {
        typingStatus.html('User is typing...');
    }
}
function updateLastTypedTime() {
    lastTypedTime = new Date();
}

setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);

#2


2  

     <script>
        function isTyping() {
                document.getElementById('typing_on').innerHTML = "User is typing...! "; }

        function  notTyping (){
       document.getElementById('typing_on').innerHTML = "No one is typing ! "; }
    </script>

    <label>
        <textarea onkeypress="setTimeout(isTyping(),4000); setInterval(notTyping,5000)"  name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </label>
    <div id="typing_on">No one is typing -blank speace.</div> 




  
  
  
    <!DOCTYPE html>
    <html>
       <head>
       </head>
       <body>

      <script>
        function isTyping() {
                document.getElementById('typing_on').innerHTML = "User is typing...! "; }
            
        function  notTyping (){
       document.getElementById('typing_on').innerHTML = "No one is typing ! "; }
    </script>

    <label>
        <textarea onkeypress="setTimeout(isTyping(),4000); setInterval(notTyping,5000)"  name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </label>
    <div id="typing_on">No one is typing -blank speace.</div> 
       </body>
    </html>

#3


1  

You can use JQuery to handle the keypress event instead of HTML. You might try something like this. Then set your default #typing on div as User is not typing.

您可以使用JQuery来处理按键事件,而不是HTML。你可以试试这个。然后在div上设置默认的#类型,因为用户没有输入。

//EXECUTES WHEN KEY IS PRESSED IN SPECIFIED ELEMENT
$("#textarea").keypress(function(){
numMiliseconds = 500;

//THIS IF STATEMENT EXECUTES IF USER CTRL-A DELETES THE TEXT BOX
if ($("textarea") == ""){
    $("#typing_on").text("User has cleared the text box");
}

$("#typing_on").text("User is typing").delay(numMiliseconds).queue(function(){
    $("#typing_on").text("User has stopped typing");
    }
});

#4


0  

Theres a nifty library plugin called underscore.js

有一个漂亮的库插件叫做underscore.js

Among its many useful functions is one called _.debounce, which can be used like so to track typing:

它有许多有用的函数,其中有一个叫做_.debounce,它可以像这样用来跟踪输入:

var typing, typingStarted, typingStopped;

typing = false;

typingStopped = _.debounce((function() {
  if (!typing) {
    return;
  }
  typing = false;
  console.log('typing is done so do what ever you need to do to notify it');
}), 5000);

typingStarted = function() {
  if (this.typing) {
    return;
  }
  typing = true;
  console.log('typing has started so do what ever you need to do to notify it');
};

document.querySelector("textarea").oninput = function(event) {
  typingStarted();
  typingStopped();
  return
};

The way this works is that on input of the text area typingStarted is called and sets typing to true preventing it from being called again. typingStopped is then called, but will only invoke the function wrapped in the _.debounce after 5000 ms which is given as the second argument to _.debounce. However if you call typingStopped again, it will reset the countdown back to 5000 ms from where ever it was at. Since typingStopped is called on each input, it will only ever execute typing = false after a full 5 seconds between key presses.

这种方法的工作方式是,在输入文本区域时,开始调用,并将类型设置为true,以防止再次调用。然后调用typingstop,但只会在5000 ms之后调用包装在_.debounce中的函数,这个函数在_.debounce的第二个参数是500ms。然而,如果你再次调用typingStopped,它将重置倒计时到5000毫秒,从原来的位置。由于在每个输入上都调用了typingstop,因此只有在按键之间满5秒后才会执行键入= false。

#1


9  

I have created a fiddle that might be helpful to you. The idea is to refresh activity message using javascript setInterval function.

我发明了一种可能对你有帮助的小提琴。其思想是使用javascript setInterval函数刷新活动消息。

var textarea = $('#textarea');
var typingStatus = $('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970, actually some time in the past
var typingDelayMillis = 5000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message

function refreshTypingStatus() {
    if (!textarea.is(':focus') || textarea.val() == '' || new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
        typingStatus.html('No one is typing -blank space.');
    } else {
        typingStatus.html('User is typing...');
    }
}
function updateLastTypedTime() {
    lastTypedTime = new Date();
}

setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);

#2


2  

     <script>
        function isTyping() {
                document.getElementById('typing_on').innerHTML = "User is typing...! "; }

        function  notTyping (){
       document.getElementById('typing_on').innerHTML = "No one is typing ! "; }
    </script>

    <label>
        <textarea onkeypress="setTimeout(isTyping(),4000); setInterval(notTyping,5000)"  name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </label>
    <div id="typing_on">No one is typing -blank speace.</div> 




  
  
  
    <!DOCTYPE html>
    <html>
       <head>
       </head>
       <body>

      <script>
        function isTyping() {
                document.getElementById('typing_on').innerHTML = "User is typing...! "; }
            
        function  notTyping (){
       document.getElementById('typing_on').innerHTML = "No one is typing ! "; }
    </script>

    <label>
        <textarea onkeypress="setTimeout(isTyping(),4000); setInterval(notTyping,5000)"  name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </label>
    <div id="typing_on">No one is typing -blank speace.</div> 
       </body>
    </html>

#3


1  

You can use JQuery to handle the keypress event instead of HTML. You might try something like this. Then set your default #typing on div as User is not typing.

您可以使用JQuery来处理按键事件,而不是HTML。你可以试试这个。然后在div上设置默认的#类型,因为用户没有输入。

//EXECUTES WHEN KEY IS PRESSED IN SPECIFIED ELEMENT
$("#textarea").keypress(function(){
numMiliseconds = 500;

//THIS IF STATEMENT EXECUTES IF USER CTRL-A DELETES THE TEXT BOX
if ($("textarea") == ""){
    $("#typing_on").text("User has cleared the text box");
}

$("#typing_on").text("User is typing").delay(numMiliseconds).queue(function(){
    $("#typing_on").text("User has stopped typing");
    }
});

#4


0  

Theres a nifty library plugin called underscore.js

有一个漂亮的库插件叫做underscore.js

Among its many useful functions is one called _.debounce, which can be used like so to track typing:

它有许多有用的函数,其中有一个叫做_.debounce,它可以像这样用来跟踪输入:

var typing, typingStarted, typingStopped;

typing = false;

typingStopped = _.debounce((function() {
  if (!typing) {
    return;
  }
  typing = false;
  console.log('typing is done so do what ever you need to do to notify it');
}), 5000);

typingStarted = function() {
  if (this.typing) {
    return;
  }
  typing = true;
  console.log('typing has started so do what ever you need to do to notify it');
};

document.querySelector("textarea").oninput = function(event) {
  typingStarted();
  typingStopped();
  return
};

The way this works is that on input of the text area typingStarted is called and sets typing to true preventing it from being called again. typingStopped is then called, but will only invoke the function wrapped in the _.debounce after 5000 ms which is given as the second argument to _.debounce. However if you call typingStopped again, it will reset the countdown back to 5000 ms from where ever it was at. Since typingStopped is called on each input, it will only ever execute typing = false after a full 5 seconds between key presses.

这种方法的工作方式是,在输入文本区域时,开始调用,并将类型设置为true,以防止再次调用。然后调用typingstop,但只会在5000 ms之后调用包装在_.debounce中的函数,这个函数在_.debounce的第二个参数是500ms。然而,如果你再次调用typingStopped,它将重置倒计时到5000毫秒,从原来的位置。由于在每个输入上都调用了typingstop,因此只有在按键之间满5秒后才会执行键入= false。